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.

Supplier and Customer layout refactor (#42)

Brad Barbinb3071e62a4ac
diff --git a/README.md b/README.md
index 40ea0a7567..409908df1a 100644
--- a/README.md
+++ b/README.md
@@ -4,14 +4,24 @@
Carbon is a high permformance, open-source, single tenant (incomplete) ERP written in Typescript. It allows customers, suppliers, and employees to share a common platform for manufacturing.
-It includes:
-
-- Magic link authentication
-- Role-based access control (RBAC)
-- Row-level security (RLS)
-- Realtime database subscriptions
-- Composable user groups
-- Full-stack type safety (Datbase → UI)
+Some of the technical highlights/roadmap are:
+
+- [x] Full-stack type safety (Datbase → UI)
+- [x] Realtime database subscriptions
+- [x] Attribute-based access control (ABAC)
+- [x] Row-level security (RLS)
+- [x] Composable user groups
+- [x] Magic link authentication
+- [x] File-based routing
+- [ ] Third-party integrations for data
+- [ ] Easy-to-use plugin system
+
+Some of the product highlights/roadmap are:
+
+- [x] Search
+- [x] Customer and supplier access
+- [ ] Double-entry accrual accounting
+- [ ] Stochastic scheduling/planning
## Project Status
diff --git a/SCHEMA.md b/SCHEMA.md
index 2936a06d1b..71feecc53b 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -1433,7 +1433,7 @@ CREATE FUNCTION public.create_customer_search_result()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.search(name, entity, uuid, link)
- VALUES (new.name, 'Customer', new.id, '/x/sales/customers/' || new.id);
+ VALUES (new.name, 'Customer', new.id, '/x/customer/' || new.id);
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
@@ -1461,7 +1461,7 @@ CREATE FUNCTION public.create_supplier_search_result()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.search(name, entity, uuid, link)
- VALUES (new.name, 'Supplier', new.id, '/x/purchasing/suppliers/' || new.id);
+ VALUES (new.name, 'Supplier', new.id, '/x/supplier/' || new.id);
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
@@ -3467,7 +3467,7 @@ END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER update_part_search_result
- AFTER UPDATE on public.customer
+ AFTER UPDATE on public.part
FOR EACH ROW EXECUTE PROCEDURE public.update_part_search_result();
@@ -4848,7 +4848,7 @@ END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER update_purchase_order_search_result
- AFTER UPDATE on public.customer
+ AFTER UPDATE on public."purchaseOrder"
FOR EACH ROW EXECUTE PROCEDURE public.update_purchase_order_search_result();
@@ -5047,6 +5047,28 @@ CREATE VIEW "suppliers_view" AS
FROM "partSupplier"
GROUP BY "supplierId"
) p ON p."supplierId" = s.id;
+
+ CREATE VIEW "customers_view" AS
+ SELECT
+ c.id,
+ c.name,
+ c."customerTypeId",
+ ct.name AS "type",
+ c."customerStatusId",
+ cs.name AS "status"
+ -- so.count AS "orderCount"
+ FROM "customer" c
+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId";
+
+ -- LEFT JOIN (
+ -- SELECT
+ -- "customerId",
+ -- COUNT(*) AS "count"
+ -- FROM "salesOrder"
+ -- GROUP BY "customerId"
+ -- ) so ON so."customerId" = c.id
+
```
@@ -6346,3 +6368,21 @@ CREATE VIEW "part_quantities_view" AS
pol."quantityToReceive"
```
+
+
+## `customer-details`
+
+```sql
+ALTER TABLE "customer"
+ ADD COLUMN "defaultCurrencyCode" TEXT,
+ ADD COLUMN "defaultPaymentTermId" TEXT,
+ ADD COLUMN "defaultShippingMethodId" TEXT,
+ ADD COLUMN "defaultShippingTermId" TEXT;
+
+ALTER TABLE "customer"
+ ADD CONSTRAINT "customer_defaultPaymentTermId_fkey" FOREIGN KEY ("defaultPaymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "customer_defaultShippingMethodId_fkey" FOREIGN KEY ("defaultShippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "customer_defaultShippingTermId_fkey" FOREIGN KEY ("defaultShippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE SET NULL;
+
+```
+
diff --git a/apps/carbon/app/components/Contact/Contact.tsx b/apps/carbon/app/components/Contact/Contact.tsx
index f067d4e870..e6d3aae006 100644
--- a/apps/carbon/app/components/Contact/Contact.tsx
+++ b/apps/carbon/app/components/Contact/Contact.tsx
@@ -1,5 +1,6 @@
import { ActionMenu, Dot } from "@carbon/react";
-import { Avatar, Grid, MenuItem, Text, VStack } from "@chakra-ui/react";
+import { Avatar, Grid, HStack, MenuItem, Text, VStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
import type { Action } from "~/types";
type ContactProps = {
@@ -8,6 +9,7 @@ type ContactProps = {
lastName: string | null;
email: string | null;
};
+ url?: string;
user?: {
id: string;
active: boolean | null;
@@ -21,7 +23,7 @@ enum UserStatus {
None,
}
-const Contact = ({ contact, user, actions }: ContactProps) => {
+const Contact = ({ contact, url, user, actions }: ContactProps) => {
const name = `${contact.firstName ?? ""} ${contact.lastName ?? ""}`;
const userStatus = user
? user.active
@@ -33,15 +35,27 @@ const Contact = ({ contact, user, actions }: ContactProps) => {
<Grid w="full" gridColumnGap={4} gridTemplateColumns="auto 1fr auto">
<Avatar size="sm" name={`${name}`} />
<VStack spacing={0} alignItems="start">
- <Text fontWeight="bold" noOfLines={1}>
- {name}
+ <HStack spacing={2}>
+ {url ? (
+ <Link to={url}>
+ <Text fontSize="sm" fontWeight="bold">
+ {name}
+ </Text>
+ </Link>
+ ) : (
+ <Text fontSize="sm" fontWeight="bold">
+ {name}
+ </Text>
+ )}
+
{userStatus === UserStatus.Active && (
<Dot color="green.400" title="Active" />
)}
{userStatus === UserStatus.Inactive && (
<Dot color="red.400" title="Inactive" />
)}
- </Text>
+ </HStack>
+
<Text fontSize="sm" color="gray.500" noOfLines={1}>
{contact.email ?? ""}
</Text>
diff --git a/apps/carbon/app/components/Form/Timezone.tsx b/apps/carbon/app/components/Form/Timezone.tsx
index 545097c991..932e5c8ca8 100644
--- a/apps/carbon/app/components/Form/Timezone.tsx
+++ b/apps/carbon/app/components/Form/Timezone.tsx
@@ -7,7 +7,7 @@ import {
} from "@chakra-ui/react";
import { useMemo } from "react";
import { useField } from "remix-validated-form";
-import { timezonesGroupedByCountry } from "~/lib/timezones";
+import { timezonesGroupedByCountry } from "~/config/timezones";
export type TimezoneProps = {
name: string;
@@ -16,7 +16,9 @@ export type TimezoneProps = {
isReadOnly?: boolean;
isLoading?: boolean;
placeholder?: string;
- onChange?: (newValue: { value: string | number; label: string }) => void;
+ onChange?: (
+ newValue: { value: string | number; label: string } | null
+ ) => void;
};
const Timezone = ({
@@ -57,7 +59,6 @@ const Timezone = ({
stringify: (option) => `${option.label}`,
})}
placeholder={placeholder ?? "Select a timezone"}
- // @ts-ignore
onChange={onChange ?? undefined}
/>
{error ? (
diff --git a/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
index f3fc51ba23..916bbcdf31 100644
--- a/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsx
@@ -6,14 +6,11 @@ import {
HStack,
} from "@chakra-ui/react";
import { Link } from "@remix-run/react";
-import type { Route } from "~/types";
+import useBreadcrumbs from "./useBreadcrumbs";
-type BreadcrumbProps = {
- links: Route[];
-};
-
-const Breadcrumbs = ({ links = [] }: BreadcrumbProps) => {
+const Breadcrumbs = () => {
const linkColor = useColor("gray.800");
+ const links = useBreadcrumbs() ?? [];
return (
<HStack>
diff --git a/apps/carbon/app/components/Layout/Topbar/Create.tsx b/apps/carbon/app/components/Layout/Topbar/Create.tsx
new file mode 100644
index 0000000000..98ceebbbd3
--- /dev/null
+++ b/apps/carbon/app/components/Layout/Topbar/Create.tsx
@@ -0,0 +1,33 @@
+import { Button, Menu, MenuButton, MenuItem, MenuList } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import useCreate from "./useCreate";
+
+const Create = () => {
+ const createLinks = useCreate();
+
+ if (!createLinks.length) return null;
+
+ return (
+ <Menu>
+ <MenuButton
+ arial-label="User Menu"
+ as={Button}
+ variant="solid"
+ colorScheme="brand"
+ size="sm"
+ cursor="pointer"
+ >
+ Create
+ </MenuButton>
+ <MenuList fontSize="sm" boxShadow="xl" minW={48}>
+ {createLinks.map((link) => (
+ <MenuItem key={link.to} as={Link} to={link.to} icon={link.icon}>
+ {link.name}
+ </MenuItem>
+ ))}
+ </MenuList>
+ </Menu>
+ );
+};
+
+export default Create;
diff --git a/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx b/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx
deleted file mode 100644
index 976d66beb5..0000000000
--- a/apps/carbon/app/components/Layout/Topbar/NewMenu.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-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();
-
- if (!newMenuLinks.length) return null;
-
- 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 d1167cffd8..e13deac4ef 100644
--- a/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/Topbar.tsx
@@ -5,12 +5,9 @@ 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";
+import Create from "./Create";
const Topbar = () => {
- const breadcrumbLinks = useBreadcrumbs();
-
const borderColor = useColor("gray.200");
return (
@@ -27,9 +24,10 @@ const Topbar = () => {
top={0}
zIndex={1}
>
- <Breadcrumbs links={breadcrumbLinks} />
+ <Breadcrumbs />
<Search />
<HStack py={2} justifyContent="end" spacing={1}>
+ <Create />
<a
target="_blank"
href="https://github.com/barbinbrad/carbon/issues/new/choose"
@@ -38,7 +36,7 @@ const Topbar = () => {
<Button
colorScheme="gray"
leftIcon={<BiHelpCircle />}
- variant="ghost"
+ variant="outline"
>
Help
</Button>
@@ -51,12 +49,11 @@ const Topbar = () => {
<Button
colorScheme="gray"
leftIcon={<BsChatSquare />}
- variant="ghost"
+ variant="outline"
>
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 3eeb7ec111..e972f8c254 100644
--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
@@ -145,6 +145,7 @@ export default function useBreadcrumbs(): Route[] {
to: "/x/purchasing/orders",
}
);
+
case "routes/x+/purchasing+/_layout":
return acc.concat({
name: "Purchasing",
@@ -155,6 +156,17 @@ export default function useBreadcrumbs(): Route[] {
name: "Orders",
to: match.pathname,
});
+ case "routes/x+/supplier+/_layout":
+ return acc.concat([
+ {
+ name: "Purchasing",
+ to: "/x/purchasing",
+ },
+ {
+ name: "Suppliers",
+ to: "/x/purchasing/suppliers",
+ },
+ ]);
case "routes/x+/purchasing+/suppliers":
return acc.concat({
name: "Suppliers",
@@ -241,6 +253,17 @@ export default function useBreadcrumbs(): Route[] {
name: "Sales",
to: match.pathname,
});
+ case "routes/x+/customer+/_layout":
+ return acc.concat([
+ {
+ name: "Sales",
+ to: match.pathname,
+ },
+ {
+ name: "Customers",
+ to: "/x/sales/customers",
+ },
+ ]);
case "routes/x+/sales+/customers":
return acc.concat({
name: "Customers",
diff --git a/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx b/apps/carbon/app/components/Layout/Topbar/useCreate.tsx
similarity index 83%
rename from apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
rename to apps/carbon/app/components/Layout/Topbar/useCreate.tsx
index 947dd35b33..936c54ab65 100644
--- a/apps/carbon/app/components/Layout/Topbar/useNewMenu.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useCreate.tsx
@@ -14,7 +14,7 @@ export default function useNewMenu(): Route[] {
let links: Route[] = [];
if (permissions.can("create", "parts")) {
links.push({
- name: "New Part",
+ name: "Part",
to: "/x/part/new",
icon: <AiOutlinePartition />,
});
@@ -22,7 +22,7 @@ export default function useNewMenu(): Route[] {
if (permissions.can("create", "purchasing")) {
links.push({
- name: "New Purchase Order",
+ name: "Purchase Order",
to: "/x/purchase-order/new",
icon: <BsCartDash />,
});
@@ -30,23 +30,23 @@ export default function useNewMenu(): Route[] {
if (permissions.can("create", "purchasing")) {
links.push({
- name: "New Supplier",
- to: "/x/purchasing/suppliers/new",
+ name: "Supplier",
+ to: "/x/supplier/new",
icon: <SiHandshake />,
});
}
if (permissions.can("create", "sales")) {
links.push({
- name: "New Customer",
- to: "/x/sales/customers/new",
+ name: "Customer",
+ to: "/x/customer/new",
icon: <IoMdPeople />,
});
}
if (permissions.can("create", "users")) {
links.push({
- name: "New Employee",
+ name: "Employee",
to: "/x/users/employees/new",
icon: <BsShieldLock />,
});
diff --git a/apps/carbon/app/lib/timezones.ts b/apps/carbon/app/config/timezones.ts
similarity index 100%
rename from apps/carbon/app/lib/timezones.ts
rename to apps/carbon/app/config/timezones.ts
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx
index a3291561b4..58a6e479be 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartForm/PartForm.tsx
@@ -18,7 +18,7 @@ import {
Submit,
TextArea,
} from "~/components/Form";
-import { usePermissions } from "~/hooks";
+import { usePermissions, useRouteData } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type {
PartGroupListItem,
@@ -42,10 +42,6 @@ type PartFormValues = {
type PartFormProps = {
initialValues: PartFormValues;
- partGroups: PartGroupListItem[];
- partTypes: PartType[];
- partReplenishmentSystems: PartReplenishmentSystem[];
- unitOfMeasures: UnitOfMeasureListItem[];
};
const useNextPartIdShortcut = () => {
@@ -93,38 +89,43 @@ const useNextPartIdShortcut = () => {
return { partId, onPartIdChange, loading };
};
-const PartForm = ({
- initialValues,
- partGroups,
- partTypes,
- partReplenishmentSystems,
- unitOfMeasures,
-}: PartFormProps) => {
+const PartForm = ({ initialValues }: PartFormProps) => {
+ const sharedPartsData = useRouteData<{
+ partGroups: PartGroupListItem[];
+ partTypes: PartType[];
+ partReplenishmentSystems: PartReplenishmentSystem[];
+ unitOfMeasures: UnitOfMeasureListItem[];
+ }>("/x/part");
+
const { partId, onPartIdChange, loading } = useNextPartIdShortcut();
const permissions = usePermissions();
const isEditing = initialValues.id !== undefined;
- const partGroupOptions = partGroups.map((partGroup) => ({
- label: partGroup.name,
- value: partGroup.id,
- }));
+ const partGroupOptions =
+ sharedPartsData?.partGroups.map((partGroup) => ({
+ label: partGroup.name,
+ value: partGroup.id,
+ })) ?? [];
- const partTypeOptions = partTypes.map((partType) => ({
- label: partType,
- value: partType,
- }));
+ const partTypeOptions =
+ sharedPartsData?.partTypes.map((partType) => ({
+ label: partType,
+ value: partType,
+ })) ?? [];
- const partReplenishmentSystemOptions = partReplenishmentSystems.map(
- (partReplenishmentSystem) => ({
- label: partReplenishmentSystem,
- value: partReplenishmentSystem,
- })
- );
+ const partReplenishmentSystemOptions =
+ sharedPartsData?.partReplenishmentSystems.map(
+ (partReplenishmentSystem) => ({
+ label: partReplenishmentSystem,
+ value: partReplenishmentSystem,
+ })
+ ) ?? [];
- const unitOfMeasureOptions = unitOfMeasures.map((uom) => ({
- label: uom.name,
- value: uom.code,
- }));
+ const unitOfMeasureOptions =
+ sharedPartsData?.unitOfMeasures.map((uom) => ({
+ label: uom.name,
+ value: uom.code,
+ })) ?? [];
return (
<ValidatedForm
diff --git a/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable/PartGroupsTable.tsx b/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable/PartGroupsTable.tsx
index fe686dbe83..e524b5a858 100644
--- a/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable/PartGroupsTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/PartGroups/PartGroupsTable/PartGroupsTable.tsx
@@ -53,7 +53,7 @@ const PartGroupsTable = memo(({ data, count }: PartGroupsTableProps) => {
navigate(`/x/parts/groups/${row.id}?${params.toString()}`);
}}
>
- View Part Group
+ Edit Part Group
</MenuItem>
<MenuItem
isDisabled={!permissions.can("delete", "parts")}
diff --git a/apps/carbon/app/modules/parts/ui/Parts/PartsTable/PartsTable.tsx b/apps/carbon/app/modules/parts/ui/Parts/PartsTable/PartsTable.tsx
index 3ecf513791..ba7ac8605d 100644
--- a/apps/carbon/app/modules/parts/ui/Parts/PartsTable/PartsTable.tsx
+++ b/apps/carbon/app/modules/parts/ui/Parts/PartsTable/PartsTable.tsx
@@ -64,7 +64,7 @@ const PartsTable = memo(({ data, count }: PartsTableProps) => {
icon={<BsPencilSquare />}
onClick={() => navigate(`/x/part/${row.id}`)}
>
- View Part
+ Edit Part
</MenuItem>
);
}, [navigate]);
diff --git a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
index 8eae156354..4ab14a6558 100644
--- a/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
+++ b/apps/carbon/app/modules/purchasing/services/purchasing.server.ts
@@ -198,18 +198,6 @@ export async function getSupplier(
return client.from("supplier").select("*").eq("id", supplierId).single();
}
-export async function getSupplierLocations(
- client: SupabaseClient<Database>,
- supplierId: string
-) {
- return client
- .from("supplierLocation")
- .select(
- "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
- )
- .eq("supplierId", supplierId);
-}
-
export async function getSupplierContact(
client: SupabaseClient<Database>,
supplierContactId: string
@@ -235,6 +223,31 @@ export async function getSupplierContacts(
.eq("supplierId", supplierId);
}
+export async function getSupplierLocations(
+ client: SupabaseClient<Database>,
+ supplierId: string
+) {
+ return client
+ .from("supplierLocation")
+ .select(
+ "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
+ )
+ .eq("supplierId", supplierId);
+}
+
+export async function getSupplierLocation(
+ client: SupabaseClient<Database>,
+ supplierContactId: string
+) {
+ return client
+ .from("supplierLocation")
+ .select(
+ "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
+ )
+ .eq("id", supplierContactId)
+ .single();
+}
+
export async function getSuppliers(
client: SupabaseClient<Database>,
args: GenericQueryFilters & {
diff --git a/apps/carbon/app/modules/purchasing/types.ts b/apps/carbon/app/modules/purchasing/types.ts
index b674503b16..53c19072cb 100644
--- a/apps/carbon/app/modules/purchasing/types.ts
+++ b/apps/carbon/app/modules/purchasing/types.ts
@@ -3,6 +3,7 @@ import type {
getExternalDocuments,
getPurchaseOrderLines,
getPurchaseOrders,
+ getSupplier,
getSupplierContacts,
getSupplierLocations,
getSuppliers,
@@ -39,6 +40,10 @@ export type Supplier = NonNullable<
Awaited<ReturnType<typeof getSuppliers>>["data"]
>[number];
+export type SupplierDetail = NonNullable<
+ Awaited<ReturnType<typeof getSupplier>>["data"]
+>;
+
export type SupplierContact = NonNullable<
Awaited<ReturnType<typeof getSupplierContacts>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
index 92f14652c4..a2d6f075e1 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader/PurchaseOrderHeader.tsx
@@ -16,7 +16,7 @@ import { usePermissions, useRouteData } from "~/hooks";
import type { PurchaseOrder } from "~/modules/purchasing";
import { usePurchaseOrder } from "../../PurchaseOrders/usePurchaseOrder";
-const PartPreview = () => {
+const PurchaseOrderHeader = () => {
const permissions = usePermissions();
const { orderId } = useParams();
if (!orderId) throw new Error("Could not find orderId");
@@ -115,4 +115,4 @@ const PartPreview = () => {
);
};
-export default PartPreview;
+export default PurchaseOrderHeader;
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
index 213d0d9bb4..28b5577635 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTableFilters/PurchaseOrdersTableFilters.tsx
@@ -5,14 +5,10 @@ import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
import { usePermissions, useUrlParams } from "~/hooks";
import { purchaseOrderStatusType } from "~/modules/purchasing";
+import { useSuppliers } from "~/stores";
-type PurchaseOrdersTableFiltersProps = {
- suppliers: { id: string | null; name: string | null }[];
-};
-
-const PurchaseOrdersTableFilters = ({
- suppliers,
-}: PurchaseOrdersTableFiltersProps) => {
+const PurchaseOrdersTableFilters = () => {
+ const [suppliers] = useSuppliers();
const [params, setParams] = useUrlParams();
const permissions = usePermissions();
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierContactsForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContactForm/SupplierContactForm.tsx
similarity index 64%
rename from apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierContactsForm.tsx
rename to apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContactForm/SupplierContactForm.tsx
index c0eeb6b047..547d708b7d 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierContactsForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContactForm/SupplierContactForm.tsx
@@ -10,7 +10,7 @@ import {
HStack,
VStack,
} from "@chakra-ui/react";
-import { useParams } from "@remix-run/react";
+import { useNavigate, useParams } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
import {
DatePicker,
@@ -21,29 +21,23 @@ import {
TextArea,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import type { SupplierContact, SupplierLocation } from "~/modules/purchasing";
import { supplierContactValidator } from "~/modules/purchasing";
+import type { TypeOfValidator } from "~/types/validators";
type SupplierContactFormProps = {
- contact?: SupplierContact;
- locations?: SupplierLocation[];
- onClose: () => void;
+ initialValues: TypeOfValidator<typeof supplierContactValidator>;
};
-const SupplierContactForm = ({
- contact,
- locations = [],
- onClose,
-}: SupplierContactFormProps) => {
+const SupplierContactForm = ({ initialValues }: SupplierContactFormProps) => {
+ const navigate = useNavigate();
const { supplierId } = useParams();
const permissions = usePermissions();
- const isEditing = !!contact?.id;
+ const isEditing = !!initialValues?.id;
const isDisabled = isEditing
? !permissions.can("update", "purchasing")
: !permissions.can("create", "purchasing");
- if (Array.isArray(contact?.contact))
- throw new Error("contact.contact is an array");
+ const onClose = () => navigate(`/x/supplier/${supplierId}/contacts`);
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
@@ -52,27 +46,10 @@ const SupplierContactForm = ({
method="post"
action={
isEditing
- ? `/x/purchasing/suppliers/${supplierId}/contact/${contact?.id}`
- : `/x/purchasing/suppliers/${supplierId}/contact/new`
+ ? `/x/supplier/${supplierId}/contacts/${initialValues?.id}`
+ : `/x/supplier/${supplierId}/contacts/new`
}
- defaultValues={{
- id: contact?.id ?? undefined,
- contactId: contact?.contact?.id ?? undefined,
- firstName: contact?.contact?.firstName ?? "",
- lastName: contact?.contact?.lastName ?? "",
- email: contact?.contact?.email ?? "",
- title: contact?.contact?.title ?? "",
- mobilePhone: contact?.contact?.mobilePhone ?? "",
- homePhone: contact?.contact?.homePhone ?? "",
- workPhone: contact?.contact?.workPhone ?? "",
- fax: contact?.contact?.fax ?? "",
- addressLine1: contact?.contact?.addressLine1 ?? "",
- addressLine2: contact?.contact?.addressLine2 ?? "",
- city: contact?.contact?.city ?? "",
- state: contact?.contact?.state ?? "",
- postalCode: contact?.contact?.postalCode ?? "",
- birthday: contact?.contact?.birthday ?? undefined,
- }}
+ defaultValues={initialValues}
onSubmit={onClose}
>
<DrawerOverlay />
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContactForm/index.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContactForm/index.tsx
new file mode 100644
index 0000000000..bb71398f9e
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContactForm/index.tsx
@@ -0,0 +1,3 @@
+import SupplierContactForm from "./SupplierContactForm";
+
+export default SupplierContactForm;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContacts/SupplierContacts.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContacts/SupplierContacts.tsx
new file mode 100644
index 0000000000..f179d43ab4
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContacts/SupplierContacts.tsx
@@ -0,0 +1,145 @@
+import {
+ Box,
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ List,
+ ListItem,
+ Text,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { Link, Outlet, useNavigate, useParams } from "@remix-run/react";
+import { useCallback, useState } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdAdd, IoMdTrash } from "react-icons/io";
+import { Contact } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import type { SupplierContact } from "~/modules/purchasing/types";
+
+type SupplierContactsProps = {
+ contacts: SupplierContact[];
+};
+
+const SupplierContacts = ({ contacts }: SupplierContactsProps) => {
+ const navigate = useNavigate();
+ const { supplierId } = useParams();
+ if (!supplierId) throw new Error("supplierId is required");
+ const permissions = usePermissions();
+ const canEdit = permissions.can("create", "purchasing");
+ const isEmpty = contacts === undefined || contacts?.length === 0;
+
+ const deleteContactModal = useDisclosure();
+ const [contact, setSelectedContact] = useState<SupplierContact>();
+
+ const getActions = useCallback(
+ (contact: SupplierContact) => {
+ const actions = [];
+ actions.push({
+ label: permissions.can("update", "purchasing")
+ ? "Edit Contact"
+ : "View Contact",
+ icon: <BsPencilSquare />,
+ onClick: () => {
+ navigate(contact.id);
+ },
+ });
+
+ if (permissions.can("delete", "purchasing")) {
+ actions.push({
+ label: "Delete Contact",
+ icon: <IoMdTrash />,
+ onClick: () => {
+ setSelectedContact(contact);
+ deleteContactModal.onOpen();
+ },
+ });
+ }
+
+ if (permissions.can("create", "users") && contact.user === null) {
+ actions.push({
+ label: "Create Account",
+ icon: <IoMdAdd />,
+ onClick: () => {
+ navigate(
+ `/x/users/suppliers/new?id=${contact.id}&supplier=${supplierId}`
+ );
+ },
+ });
+ }
+
+ if (permissions.can("create", "resources")) {
+ actions.push({
+ label: "Add Contractor",
+ icon: <IoMdAdd />,
+ onClick: () => {
+ navigate(
+ `/x/resources/contractors/new?id=${contact.id}&supplierId=${supplierId}`
+ );
+ },
+ });
+ }
+
+ return actions;
+ },
+ [permissions, deleteContactModal, navigate, supplierId]
+ );
+
+ return (
+ <>
+ <Card w="full">
+ <CardHeader display="flex" justifyContent="space-between">
+ <Heading size="md" display="inline-flex">
+ Contacts
+ </Heading>
+ {canEdit && (
+ <Button colorScheme="brand" as={Link} to="new">
+ New
+ </Button>
+ )}
+ </CardHeader>
+ <CardBody>
+ {isEmpty ? (
+ <Box w="full" my={8} textAlign="center">
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any contacts yet.
+ </Text>
+ </Box>
+ ) : (
+ <List w="full" spacing={4}>
+ {contacts?.map((contact) => (
+ <ListItem key={contact.id}>
+ {contact.contact &&
+ !Array.isArray(contact.contact) &&
+ !Array.isArray(contact.user) ? (
+ <Contact
+ contact={contact.contact}
+ url={`/x/supplier/${supplierId}/contacts/${contact.id}`}
+ user={contact.user}
+ actions={getActions(contact)}
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ </CardBody>
+ </Card>
+
+ <ConfirmDelete
+ action={`/x/supplier/${supplierId}/contacts/delete/${contact?.id}`}
+ isOpen={deleteContactModal.isOpen}
+ name={`${contact?.contact?.firstName} ${contact?.contact?.lastName}`}
+ text="Are you sure you want to delete this contact?"
+ onCancel={deleteContactModal.onClose}
+ onSubmit={deleteContactModal.onClose}
+ />
+
+ <Outlet />
+ </>
+ );
+};
+
+export default SupplierContacts;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContacts/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContacts/index.ts
new file mode 100644
index 0000000000..4e6da35e8f
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierContacts/index.ts
@@ -0,0 +1,3 @@
+import SupplierContacts from "./SupplierContacts";
+
+export default SupplierContacts;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/SupplierForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/SupplierForm.tsx
new file mode 100644
index 0000000000..ced2b38c9b
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/SupplierForm.tsx
@@ -0,0 +1,187 @@
+import {
+ Button,
+ Card,
+ CardBody,
+ CardFooter,
+ CardHeader,
+ Grid,
+ Heading,
+ HStack,
+ Text,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Currency,
+ Employee,
+ Hidden,
+ Input,
+ Select,
+ Submit,
+} from "~/components/Form";
+import { usePermissions, useRouteData } from "~/hooks";
+import type { SupplierStatus, SupplierType } from "~/modules/purchasing";
+import { supplierValidator } from "~/modules/purchasing";
+import type { ListItem } from "~/types";
+import type { TypeOfValidator } from "~/types/validators";
+
+type SupplierFormProps = {
+ initialValues: TypeOfValidator<typeof supplierValidator>;
+};
+
+const SupplierForm = ({ initialValues }: SupplierFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate("/x/purchasing/suppliers");
+
+ const routeData = useRouteData<{
+ supplierTypes: SupplierType[];
+ supplierStatuses: SupplierStatus[];
+ paymentTerms: ListItem[];
+ shippingMethods: ListItem[];
+ shippingTerms: ListItem[];
+ }>("/x/supplier");
+
+ const supplierTypeOptions =
+ routeData?.supplierTypes?.map((type) => ({
+ value: type.id,
+ label: type.name,
+ })) ?? [];
+
+ const supplierStatusOptions =
+ routeData?.supplierStatuses?.map((status) => ({
+ value: status.id,
+ label: status.name,
+ })) ?? [];
+
+ const paymentTermOptions =
+ routeData?.paymentTerms?.map((term) => ({
+ value: term.id,
+ label: term.name,
+ })) ?? [];
+
+ const shippingMethodOptions =
+ routeData?.shippingMethods?.map((method) => ({
+ value: method.id,
+ label: method.name,
+ })) ?? [];
+
+ const shippingTermOptions =
+ routeData?.shippingTerms?.map((term) => ({
+ value: term.id,
+ label: term.name,
+ })) ?? [];
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "purchasing")
+ : !permissions.can("create", "purchasing");
+
+ return (
+ <ValidatedForm
+ method="post"
+ validator={supplierValidator}
+ defaultValues={initialValues}
+ >
+ <Card w="full">
+ <CardHeader>
+ <Heading size="md">
+ {isEditing ? "Supplier Basics" : "New Supplier"}
+ </Heading>
+ {!isEditing && (
+ <Text color="gray.500">
+ A supplier is a business or person who sells you parts or
+ services.
+ </Text>
+ )}
+ </CardHeader>
+ <CardBody>
+ <Hidden name="id" />
+ <Grid
+ gridTemplateColumns={
+ isEditing ? ["1fr", "1fr", "1fr 1fr 1fr"] : "1fr"
+ }
+ gridColumnGap={8}
+ gridRowGap={2}
+ w="full"
+ >
+ <VStack alignItems="start" spacing={2} w="full">
+ <Input name="name" label="Name" />
+ <Input name="taxId" label="Tax ID" />
+ <Select
+ name="supplierTypeId"
+ label="Supplier Type"
+ options={supplierTypeOptions}
+ placeholder="Select Supplier Type"
+ />
+ </VStack>
+ {isEditing && (
+ <>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Employee name="accountManagerId" label="Account Manager" />
+ <Select
+ name="supplierStatusId"
+ label="Supplier Status"
+ options={supplierStatusOptions}
+ placeholder="Select Supplier Status"
+ />
+ <Currency
+ name="defaultCurrencyCode"
+ label="Currency"
+ placeholder="Default Currency"
+ />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Select
+ name="defaultPaymentTermId"
+ label="Payment Term"
+ options={paymentTermOptions}
+ placeholder="Default Payment Term"
+ />
+ <Select
+ name="defaultShippingMethodId"
+ label="Shipping Method"
+ options={shippingMethodOptions}
+ placeholder="Default Shipping Method"
+ />
+ <Select
+ name="defaultShippingTermId"
+ label="Shipping Term"
+ options={shippingTermOptions}
+ placeholder="Default Shipping Term"
+ />
+ </VStack>
+ </>
+ )}
+
+ {/* <SupplierLocations
+ locations={locations}
+ isEditing={isEditing}
+ />
+ <SupplierContacts
+ contacts={contacts}
+ locations={locations}
+ isEditing={isEditing}
+ /> */}
+ </Grid>
+ </CardBody>
+ <CardFooter>
+ <HStack spacing={2}>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </CardFooter>
+ </Card>
+ </ValidatedForm>
+ );
+};
+
+export default SupplierForm;
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/index.ts
similarity index 100%
rename from apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/index.ts
rename to apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm/index.ts
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader/SupplierHeader.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader/SupplierHeader.tsx
new file mode 100644
index 0000000000..5e3ff8d4e6
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader/SupplierHeader.tsx
@@ -0,0 +1,94 @@
+import {
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ HStack,
+ Stack,
+ Text,
+ VStack,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { FaHistory } from "react-icons/fa";
+import { useRouteData } from "~/hooks";
+import type {
+ SupplierDetail,
+ SupplierStatus,
+ SupplierType,
+} from "~/modules/purchasing";
+import type { ListItem } from "~/types";
+
+const SupplierHeader = () => {
+ const { supplierId } = useParams();
+ if (!supplierId) throw new Error("Could not find supplierId");
+ const routeData = useRouteData<{ supplier: SupplierDetail }>(
+ `/x/supplier/${supplierId}`
+ );
+ const sharedSupplierData = useRouteData<{
+ supplierTypes: SupplierType[];
+ supplierStatuses: SupplierStatus[];
+ paymentTerms: ListItem[];
+ }>("/x/supplier");
+
+ return (
+ <VStack w="full" alignItems="start" spacing={2}>
+ <Card w="full">
+ <CardHeader>
+ <HStack justifyContent="space-between" alignItems="start">
+ <Stack direction="column" spacing={2}>
+ <Heading size="md">{routeData?.supplier?.name}</Heading>
+ </Stack>
+ <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
+ Supplier Details
+ </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">Type</Text>
+ <Text fontWeight="bold">
+ {sharedSupplierData?.supplierTypes?.find(
+ (type) => type.id === routeData?.supplier?.supplierTypeId
+ )?.name ?? "--"}
+ </Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Status</Text>
+ <Text fontWeight="bold">
+ {sharedSupplierData?.supplierStatuses?.find(
+ (status) =>
+ status.id === routeData?.supplier?.supplierStatusId
+ )?.name ?? "--"}
+ </Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Payment Terms</Text>
+ <Text fontWeight="bold">
+ {sharedSupplierData?.paymentTerms?.find(
+ (term) =>
+ term.id === routeData?.supplier?.defaultPaymentTermId
+ )?.name ?? "--"}
+ </Text>
+ </Stack>
+ </Stack>
+ </CardBody>
+ </Card>
+ </VStack>
+ );
+};
+
+export default SupplierHeader;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader/index.ts
new file mode 100644
index 0000000000..bb88c2030d
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierHeader/index.ts
@@ -0,0 +1,3 @@
+import SupplierHeader from "./SupplierHeader";
+
+export default SupplierHeader;
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierLocationForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm/SupplierLocationForm.tsx
similarity index 68%
rename from apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierLocationForm.tsx
rename to apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm/SupplierLocationForm.tsx
index e126a5551f..c861bc663f 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierLocationForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm/SupplierLocationForm.tsx
@@ -10,31 +10,27 @@ import {
HStack,
VStack,
} from "@chakra-ui/react";
-import { useParams } from "@remix-run/react";
+import { useNavigate, useParams } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
import { Hidden, Input, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
-import type { SupplierLocation } from "~/modules/purchasing";
import { supplierLocationValidator } from "~/modules/purchasing";
+import type { TypeOfValidator } from "~/types/validators";
type SupplierLocationFormProps = {
- location?: SupplierLocation;
- onClose: () => void;
+ initialValues: TypeOfValidator<typeof supplierLocationValidator>;
};
-const SupplierLocationForm = ({
- location,
- onClose,
-}: SupplierLocationFormProps) => {
+const SupplierLocationForm = ({ initialValues }: SupplierLocationFormProps) => {
+ const navigate = useNavigate();
const { supplierId } = useParams();
const permissions = usePermissions();
- const isEditing = !!location?.id;
+ const isEditing = !!initialValues?.id;
const isDisabled = isEditing
? !permissions.can("update", "purchasing")
: !permissions.can("create", "purchasing");
- if (Array.isArray(location?.address))
- throw new Error("location.address is an array");
+ const onClose = () => navigate(`/x/supplier/${supplierId}/locations`);
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
@@ -43,19 +39,10 @@ const SupplierLocationForm = ({
method="post"
action={
isEditing
- ? `/x/purchasing/suppliers/${supplierId}/location/${location?.id}`
- : `/x/purchasing/suppliers/${supplierId}/location/new`
+ ? `/x/supplier/${supplierId}/locations/${initialValues?.id}`
+ : `/x/supplier/${supplierId}/locations/new`
}
- defaultValues={{
- id: location?.id ?? undefined,
- addressId: location?.address?.id ?? undefined,
-
- addressLine1: location?.address?.addressLine1 ?? "",
- addressLine2: location?.address?.addressLine2 ?? "",
- city: location?.address?.city ?? "",
- state: location?.address?.state ?? "",
- postalCode: location?.address?.postalCode ?? "",
- }}
+ defaultValues={initialValues}
onSubmit={onClose}
>
<DrawerOverlay />
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm/index.ts
new file mode 100644
index 0000000000..3f1859db3c
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocationForm/index.ts
@@ -0,0 +1,3 @@
+import SupplierLocationForm from "./SupplierLocationForm";
+
+export default SupplierLocationForm;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocations/SupplierLocations.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocations/SupplierLocations.tsx
new file mode 100644
index 0000000000..3814d8736c
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocations/SupplierLocations.tsx
@@ -0,0 +1,130 @@
+import {
+ Box,
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ List,
+ ListItem,
+ Text,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { Link, Outlet, useNavigate, useParams } from "@remix-run/react";
+import { useCallback, useState } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdAdd, IoMdTrash } from "react-icons/io";
+import { Address } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import type { SupplierLocation } from "~/modules/purchasing/types";
+
+type SupplierLocationsProps = {
+ locations: SupplierLocation[];
+};
+
+const SupplierLocations = ({ locations }: SupplierLocationsProps) => {
+ const navigate = useNavigate();
+ const { supplierId } = useParams();
+ if (!supplierId) throw new Error("supplierId is required");
+ const permissions = usePermissions();
+ const canEdit = permissions.can("create", "purchasing");
+ const isEmpty = locations === undefined || locations?.length === 0;
+
+ const deleteLocationModal = useDisclosure();
+ const [location, setSelectedLocation] = useState<SupplierLocation>();
+
+ const getActions = useCallback(
+ (location: SupplierLocation) => {
+ const actions = [];
+ if (permissions.can("update", "purchasing")) {
+ actions.push({
+ label: "Edit Location",
+ icon: <BsPencilSquare />,
+ onClick: () => {
+ navigate(location.id);
+ },
+ });
+ }
+ if (permissions.can("delete", "purchasing")) {
+ actions.push({
+ label: "Delete Location",
+ icon: <IoMdTrash />,
+ onClick: () => {
+ setSelectedLocation(location);
+ deleteLocationModal.onOpen();
+ },
+ });
+ }
+
+ if (permissions.can("create", "resources")) {
+ actions.push({
+ label: "Add Partner",
+ icon: <IoMdAdd />,
+ onClick: () => {
+ navigate(
+ `/x/resources/partners/new?id=${location.id}&supplierId=${supplierId}`
+ );
+ },
+ });
+ }
+
+ return actions;
+ },
+ [permissions, deleteLocationModal, navigate, supplierId]
+ );
+
+ return (
+ <>
+ <Card w="full">
+ <CardHeader display="flex" justifyContent="space-between">
+ <Heading size="md" display="inline-flex">
+ Locations
+ </Heading>
+ {canEdit && (
+ <Button colorScheme="brand" as={Link} to="new">
+ New
+ </Button>
+ )}
+ </CardHeader>
+ <CardBody>
+ {isEmpty ? (
+ <Box w="full" my={8} textAlign="center">
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any locations yet.
+ </Text>
+ </Box>
+ ) : (
+ <List w="full" spacing={4}>
+ {locations?.map((location) => (
+ <ListItem key={location.id}>
+ {location.address && !Array.isArray(location.address) ? (
+ <Address
+ address={location.address}
+ actions={getActions(location)}
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ </CardBody>
+ </Card>
+
+ {deleteLocationModal.isOpen && (
+ <ConfirmDelete
+ action={`/x/supplier/${supplierId}/locations/delete/${location?.id}`}
+ // @ts-ignore
+ name={location?.address?.city ?? ""}
+ text="Are you sure you want to delete this location?"
+ onCancel={deleteLocationModal.onClose}
+ onSubmit={deleteLocationModal.onClose}
+ />
+ )}
+
+ <Outlet />
+ </>
+ );
+};
+
+export default SupplierLocations;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocations/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocations/index.ts
new file mode 100644
index 0000000000..307b65b822
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierLocations/index.ts
@@ -0,0 +1,3 @@
+import SupplierLocations from "./SupplierLocations";
+
+export default SupplierLocations;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/SupplierSidebar.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/SupplierSidebar.tsx
new file mode 100644
index 0000000000..eec1568bf8
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/SupplierSidebar.tsx
@@ -0,0 +1,70 @@
+import { Count, useColor } from "@carbon/react";
+import { Box, Button, VStack } from "@chakra-ui/react";
+import { Link, useMatches, useParams } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type {
+ SupplierContact,
+ SupplierDetail,
+ SupplierLocation,
+} from "~/modules/purchasing";
+import { useSupplierSidebar } from "./useSupplierSidebar";
+
+const SupplierSidebar = () => {
+ const { supplierId } = useParams();
+ const borderColor = useColor("gray.200");
+ if (!supplierId)
+ throw new Error(
+ "SupplierSidebar requires an supplierId and could not find supplierId in params"
+ );
+
+ const routeData = useRouteData<{
+ purchaseOrder: SupplierDetail;
+ contacts: SupplierContact[];
+ locations: SupplierLocation[];
+ }>(`/x/supplier/${supplierId}`);
+ const links = useSupplierSidebar({
+ contacts: routeData?.contacts.length ?? 0,
+ locations: routeData?.locations.length ?? 0,
+ });
+ 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={isActive ? "1px solid" : "none"}
+ borderColor={borderColor}
+ fontWeight={isActive ? "bold" : "normal"}
+ justifyContent={
+ route.count === undefined ? "start" : "space-between"
+ }
+ size="md"
+ w="full"
+ >
+ <span>{route.name}</span>
+ {route.count !== undefined && <Count count={route.count} />}
+ </Button>
+ );
+ })}
+ </VStack>
+ </VStack>
+ </Box>
+ </VStack>
+ );
+};
+
+export default SupplierSidebar;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/index.ts
new file mode 100644
index 0000000000..ed3b74a137
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/index.ts
@@ -0,0 +1,3 @@
+import SupplierSidebar from "./SupplierSidebar";
+
+export default SupplierSidebar;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx
new file mode 100644
index 0000000000..1cdeda2a8d
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx
@@ -0,0 +1,33 @@
+import { usePermissions } from "~/hooks";
+import type { Role } from "~/types";
+
+type Props = {
+ contacts: number;
+ locations: number;
+};
+
+export function useSupplierSidebar({ contacts, locations }: Props) {
+ const permissions = usePermissions();
+ return [
+ {
+ name: "Summary",
+ to: "",
+ },
+ {
+ name: "Contacts",
+ to: "contacts",
+ role: ["employee"],
+ count: contacts,
+ },
+ {
+ name: "Locations",
+ to: "locations",
+ role: ["employee", "supplier"],
+ count: locations,
+ },
+ ].filter(
+ (item) =>
+ item.role === undefined ||
+ item.role.some((role) => permissions.is(role as Role))
+ );
+}
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/index.ts
new file mode 100644
index 0000000000..ee928b7b39
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/index.ts
@@ -0,0 +1,17 @@
+import SupplierContactForm from "./SupplierContactForm";
+import SupplierContacts from "./SupplierContacts";
+import SupplierForm from "./SupplierForm";
+import SupplierHeader from "./SupplierHeader";
+import SupplierLocationForm from "./SupplierLocationForm";
+import SupplierLocations from "./SupplierLocations";
+import SupplierSidebar from "./SupplierSidebar";
+
+export {
+ SupplierContactForm,
+ SupplierContacts,
+ SupplierForm,
+ SupplierHeader,
+ SupplierLocationForm,
+ SupplierLocations,
+ SupplierSidebar,
+};
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/SupplierForm.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/SupplierForm.tsx
deleted file mode 100644
index 397054dd5f..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/SupplierForm.tsx
+++ /dev/null
@@ -1,201 +0,0 @@
-import {
- Box,
- Button,
- Drawer,
- DrawerBody,
- DrawerCloseButton,
- DrawerContent,
- DrawerFooter,
- DrawerHeader,
- DrawerOverlay,
- Grid,
- HStack,
- VStack,
-} from "@chakra-ui/react";
-import { useNavigate } from "@remix-run/react";
-import { ValidatedForm } from "remix-validated-form";
-import {
- Currency,
- Employee,
- Hidden,
- Input,
- Select,
- Submit,
-} from "~/components/Form";
-import { usePermissions, useRouteData } from "~/hooks";
-import type {
- SupplierContact,
- SupplierLocation,
- SupplierStatus,
- SupplierType,
-} from "~/modules/purchasing";
-import { supplierValidator } from "~/modules/purchasing";
-import type { ListItem } from "~/types";
-import type { TypeOfValidator } from "~/types/validators";
-import { SupplierContacts, SupplierLocations } from "./components";
-
-type SupplierFormProps = {
- initialValues: TypeOfValidator<typeof supplierValidator>;
- contacts?: SupplierContact[];
- locations?: SupplierLocation[];
-};
-
-const SupplierForm = ({
- initialValues,
- contacts,
- locations,
-}: SupplierFormProps) => {
- const permissions = usePermissions();
- const navigate = useNavigate();
- const onClose = () => navigate("/x/purchasing/suppliers");
-
- const routeData = useRouteData<{
- supplierTypes: SupplierType[];
- supplierStatuses: SupplierStatus[];
- paymentTerms: ListItem[];
- shippingMethods: ListItem[];
- shippingTerms: ListItem[];
- }>("/x/purchasing/suppliers");
-
- const supplierTypeOptions =
- routeData?.supplierTypes?.map((type) => ({
- value: type.id,
- label: type.name,
- })) ?? [];
-
- const supplierStatusOptions =
- routeData?.supplierStatuses?.map((status) => ({
- value: status.id,
- label: status.name,
- })) ?? [];
-
- const paymentTermOptions =
- routeData?.paymentTerms?.map((term) => ({
- value: term.id,
- label: term.name,
- })) ?? [];
-
- const shippingMethodOptions =
- routeData?.shippingMethods?.map((method) => ({
- value: method.id,
- label: method.name,
- })) ?? [];
-
- const shippingTermOptions =
- routeData?.shippingTerms?.map((term) => ({
- value: term.id,
- label: term.name,
- })) ?? [];
-
- const isEditing = initialValues.id !== undefined;
- const isDisabled = isEditing
- ? !permissions.can("update", "purchasing")
- : !permissions.can("create", "purchasing");
-
- return (
- <Drawer onClose={onClose} isOpen size="full">
- <ValidatedForm
- method="post"
- action={
- isEditing
- ? `/x/purchasing/suppliers/${initialValues.id}`
- : "/x/purchasing/suppliers/new"
- }
- validator={supplierValidator}
- defaultValues={initialValues}
- >
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>
- {isEditing ? initialValues.name : "New Supplier"}
- </DrawerHeader>
- <DrawerBody>
- <Grid
- gridTemplateColumns={["1fr", "1fr", "5fr 2fr"]}
- gridColumnGap={8}
- w="full"
- >
- <Box w="full">
- <Hidden name="id" />
- <VStack spacing={4} w="full" alignItems="start">
- <Grid
- gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
- gridColumnGap={8}
- gridRowGap={4}
- w="full"
- >
- <Input name="name" label="Name" />
- <Input name="taxId" label="Tax ID" />
- <Select
- name="supplierTypeId"
- label="Supplier Type"
- options={supplierTypeOptions}
- placeholder="Select Supplier Type"
- />
- <Employee name="accountManagerId" label="Account Manager" />
- <Select
- name="supplierStatusId"
- label="Supplier Status"
- options={supplierStatusOptions}
- placeholder="Select Supplier Status"
- />
- <Currency
- name="defaultCurrencyCode"
- label="Currency"
- placeholder="Default Currency"
- />
- <Select
- name="defaultPaymentTermId"
- label="Payment Term"
- options={paymentTermOptions}
- placeholder="Default Payment Term"
- />
- <Select
- name="defaultShippingMethodId"
- label="Shipping Method"
- options={shippingMethodOptions}
- placeholder="Default Shipping Method"
- />
- <Select
- name="defaultShippingTermId"
- label="Shipping Term"
- options={shippingTermOptions}
- placeholder="Default Shipping Term"
- />
- </Grid>
- </VStack>
- </Box>
- <VStack spacing={8} w="full" alignItems="start" py={[8, 8, 0]}>
- <SupplierLocations
- locations={locations}
- isEditing={isEditing}
- />
- <SupplierContacts
- contacts={contacts}
- locations={locations}
- isEditing={isEditing}
- />
- </VStack>
- </Grid>
- </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 SupplierForm;
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierContacts.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierContacts.tsx
deleted file mode 100644
index 9ba175e121..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierContacts.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-import {
- Button,
- HStack,
- Heading,
- IconButton,
- List,
- ListItem,
- Text,
- VStack,
- useDisclosure,
-} from "@chakra-ui/react";
-import { useNavigate, useParams } from "@remix-run/react";
-import { useCallback, useState } from "react";
-import { BsPencilSquare } from "react-icons/bs";
-import { IoMdAdd, IoMdTrash } from "react-icons/io";
-import { Contact } from "~/components";
-import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions } from "~/hooks";
-import type { SupplierContact, SupplierLocation } from "~/modules/purchasing";
-import SupplierContactForm from "./SupplierContactsForm";
-
-type SupplierContactProps = {
- contacts?: SupplierContact[];
- locations?: SupplierLocation[];
- isEditing?: boolean;
-};
-
-const SupplierContacts = ({
- contacts = [],
- locations = [],
- isEditing = false,
-}: SupplierContactProps) => {
- const { supplierId } = useParams();
- const navigate = useNavigate();
- const permissions = usePermissions();
-
- const [contact, setContact] = useState<SupplierContact | undefined>(
- undefined
- );
-
- const contactDrawer = useDisclosure();
- const deleteContactModal = useDisclosure();
-
- const isEmpty = contacts === undefined || contacts?.length === 0;
-
- const getActions = useCallback(
- (contact: SupplierContact) => {
- const actions = [];
- if (permissions.can("update", "purchasing")) {
- actions.push({
- label: "Edit Contact",
- icon: <BsPencilSquare />,
- onClick: () => {
- setContact(contact);
- contactDrawer.onOpen();
- },
- });
- }
- if (permissions.can("delete", "purchasing")) {
- actions.push({
- label: "Delete Contact",
- icon: <IoMdTrash />,
- onClick: () => {
- setContact(contact);
- deleteContactModal.onOpen();
- },
- });
- }
-
- if (permissions.can("create", "users") && contact.user === null) {
- actions.push({
- label: "Create Account",
- icon: <IoMdAdd />,
- onClick: () => {
- navigate(
- `/x/users/suppliers/new?id=${contact.id}&supplier=${supplierId}`
- );
- },
- });
- }
-
- if (permissions.can("create", "resources")) {
- actions.push({
- label: "Add Contractor",
- icon: <IoMdAdd />,
- onClick: () => {
- navigate(
- `/x/resources/contractors/new?id=${contact.id}&supplierId=${supplierId}`
- );
- },
- });
- }
-
- return actions;
- },
- [permissions, supplierId, contactDrawer, deleteContactModal, navigate]
- );
-
- return (
- <>
- <VStack alignItems="start" w="full" spacing={4} mb={4}>
- <HStack w="full" justifyContent="space-between">
- <Heading size="md">Contacts</Heading>
- {permissions.can("create", "purchasing") && (
- <IconButton
- icon={<IoMdAdd />}
- aria-label="Add contact"
- variant="outline"
- onClick={() => {
- setContact(undefined);
- contactDrawer.onOpen();
- }}
- />
- )}
- </HStack>
- {isEmpty && (
- <Text color="gray.500" fontSize="sm">
- You haven’t created any contacts yet.
- </Text>
- )}
- {!isEmpty && (
- <List w="full" spacing={4}>
- {contacts?.map((contact) => (
- <ListItem key={contact.id}>
- {contact.contact &&
- !Array.isArray(contact.contact) &&
- !Array.isArray(contact.user) ? (
- <Contact
- contact={contact.contact}
- user={contact.user}
- actions={getActions(contact)}
- />
- ) : null}
- </ListItem>
- ))}
- </List>
- )}
- {isEmpty && permissions.can("create", "purchasing") && (
- <Button
- leftIcon={<IoMdAdd />}
- colorScheme="brand"
- onClick={() => {
- setContact(undefined);
- contactDrawer.onOpen();
- }}
- isDisabled={!isEditing}
- >
- New Contact
- </Button>
- )}
- </VStack>
- {contactDrawer.isOpen && (
- <SupplierContactForm
- onClose={contactDrawer.onClose}
- contact={contact}
- locations={locations}
- />
- )}
- {deleteContactModal.isOpen && (
- <ConfirmDelete
- action={`/x/purchasing/suppliers/${supplierId}/contact/delete/${contact?.id}`}
- // @ts-ignore
- name={`${contact?.contact.firstName} ${contact?.contact.lastName}`}
- text="Are you sure you want to delete this contact?"
- onCancel={deleteContactModal.onClose}
- onSubmit={deleteContactModal.onClose}
- />
- )}
- </>
- );
-};
-
-export default SupplierContacts;
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierLocations.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierLocations.tsx
deleted file mode 100644
index 48dc49b6ff..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/SupplierLocations.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import {
- Button,
- Heading,
- HStack,
- IconButton,
- List,
- ListItem,
- Text,
- VStack,
- useDisclosure,
-} from "@chakra-ui/react";
-import { useNavigate, useParams } from "@remix-run/react";
-import { useCallback, useState } from "react";
-import { BsPencilSquare } from "react-icons/bs";
-import { IoMdAdd, IoMdTrash } from "react-icons/io";
-import { Address } from "~/components";
-import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions } from "~/hooks";
-import type { SupplierLocation } from "~/modules/purchasing";
-import SupplierLocationForm from "./SupplierLocationForm";
-
-type SupplierLocationProps = {
- locations?: SupplierLocation[];
- isEditing?: boolean;
-};
-
-const SupplierLocations = ({
- locations = [],
- isEditing = false,
-}: SupplierLocationProps) => {
- const navigate = useNavigate();
- const permissions = usePermissions();
- const locationDrawer = useDisclosure();
- const deleteContactModal = useDisclosure();
-
- const { supplierId } = useParams();
-
- const [location, setLocation] = useState<SupplierLocation | undefined>(
- undefined
- );
-
- const isEmpty = locations === undefined || locations?.length === 0;
-
- const getActions = useCallback(
- (location: SupplierLocation) => {
- const actions = [];
- if (permissions.can("update", "purchasing")) {
- actions.push({
- label: "Edit Location",
- icon: <BsPencilSquare />,
- onClick: () => {
- setLocation(location);
- locationDrawer.onOpen();
- },
- });
- }
- if (permissions.can("delete", "purchasing")) {
- actions.push({
- label: "Delete Location",
- icon: <IoMdTrash />,
- onClick: () => {
- setLocation(location);
- deleteContactModal.onOpen();
- },
- });
- }
- if (permissions.can("create", "resources")) {
- actions.push({
- label: "Add Partner",
- icon: <IoMdAdd />,
- onClick: () => {
- navigate(
- `/x/resources/partners/new?id=${location.id}&supplierId=${supplierId}`
- );
- },
- });
- }
- return actions;
- },
- [permissions, locationDrawer, deleteContactModal, navigate, supplierId]
- );
-
- return (
- <>
- <VStack alignItems="start" w="full" spacing={4} mb={4}>
- <HStack w="full" justifyContent="space-between">
- <Heading size="md">Locations</Heading>
- {permissions.can("create", "purchasing") && (
- <IconButton
- icon={<IoMdAdd />}
- aria-label="Add location"
- variant="outline"
- onClick={() => {
- setLocation(undefined);
- locationDrawer.onOpen();
- }}
- />
- )}
- </HStack>
- {isEmpty && (
- <Text color="gray.500" fontSize="sm">
- You haven’t created any locations yet.
- </Text>
- )}
- {!isEmpty && (
- <List w="full" spacing={4}>
- {locations?.map((location) => (
- <ListItem key={location.id}>
- {location.address && !Array.isArray(location.address) ? (
- <Address
- address={location.address}
- actions={getActions(location)}
- />
- ) : null}
- </ListItem>
- ))}
- </List>
- )}
- {isEmpty && permissions.can("create", "purchasing") && (
- <Button
- leftIcon={<IoMdAdd />}
- colorScheme="brand"
- onClick={() => {
- setLocation(undefined);
- locationDrawer.onOpen();
- }}
- isDisabled={!isEditing}
- >
- New Location
- </Button>
- )}
- </VStack>
- {locationDrawer.isOpen && (
- <SupplierLocationForm
- onClose={locationDrawer.onClose}
- location={location}
- />
- )}
- {deleteContactModal.isOpen && (
- <ConfirmDelete
- action={`/x/purchasing/suppliers/${supplierId}/location/delete/${location?.id}`}
- // @ts-ignore
- name={location?.address?.city ?? ""}
- text="Are you sure you want to delete this location?"
- onCancel={deleteContactModal.onClose}
- onSubmit={deleteContactModal.onClose}
- />
- )}
- </>
- );
-};
-
-export default SupplierLocations;
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/index.ts b/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/index.ts
deleted file mode 100644
index 856b54a2f5..0000000000
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SupplierForm/components/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import SupplierContacts from "./SupplierContacts";
-import SupplierLocations from "./SupplierLocations";
-
-export { SupplierContacts, SupplierLocations };
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable/SuppliersTable.tsx
index 9341c399d5..88ae4d7662 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable/SuppliersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable/SuppliersTable.tsx
@@ -10,7 +10,6 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { BsPencilSquare, BsPlus } from "react-icons/bs";
import { Table } from "~/components";
-import { useUrlParams } from "~/hooks";
import type { Supplier } from "~/modules/purchasing";
type SuppliersTableProps = {
@@ -20,7 +19,6 @@ type SuppliersTableProps = {
const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
const navigate = useNavigate();
- const [params] = useUrlParams();
const columns = useMemo<ColumnDef<Supplier>[]>(() => {
return [
@@ -28,7 +26,7 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
accessorKey: "name",
header: "Name",
cell: ({ row }) => (
- <Link onClick={() => navigate(row.original.id as string)}>
+ <Link onClick={() => navigate(`/x/supplier/${row.original.id}`)}>
{row.original.name}
</Link>
),
@@ -88,8 +86,7 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
),
},
];
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [params]);
+ }, [navigate]);
const renderContextMenu = useMemo(
// eslint-disable-next-line react/display-name
@@ -97,14 +94,12 @@ const SuppliersTable = memo(({ data, count }: SuppliersTableProps) => {
(
<MenuItem
icon={<BsPencilSquare />}
- onClick={() =>
- navigate(`/x/purchasing/suppliers/${row.id}?${params.toString()}`)
- }
+ onClick={() => navigate(`/x/supplier/${row.id}`)}
>
- View Supplier
+ Edit Supplier
</MenuItem>
),
- [navigate, params]
+ [navigate]
);
return (
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
index a26baf3156..81d90d227e 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTableFilters/SuppliersTableFilters.tsx
@@ -84,7 +84,7 @@ const SuppliersTableFilters = ({
{permissions.can("create", "purchasing") && (
<Button
as={Link}
- to={`new?${params.toString()}`}
+ to={`/x/supplier/new`}
colorScheme="brand"
leftIcon={<IoMdAdd />}
>
diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/index.ts b/apps/carbon/app/modules/purchasing/ui/Suppliers/index.ts
index 919c9675a2..699f48a444 100644
--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/index.ts
+++ b/apps/carbon/app/modules/purchasing/ui/Suppliers/index.ts
@@ -1,5 +1,4 @@
-import SupplierForm from "./SupplierForm";
import SuppliersTable from "./SuppliersTable";
import SuppliersTableFilters from "./SuppliersTableFilters";
-export { SupplierForm, SuppliersTable, SuppliersTableFilters };
+export { SuppliersTable, SuppliersTableFilters };
diff --git a/apps/carbon/app/modules/purchasing/ui/index.ts b/apps/carbon/app/modules/purchasing/ui/index.ts
index a02c6ef3b2..9acc07cbed 100644
--- a/apps/carbon/app/modules/purchasing/ui/index.ts
+++ b/apps/carbon/app/modules/purchasing/ui/index.ts
@@ -1,7 +1,8 @@
import usePurchasingSidebar from "./usePurchasingSidebar";
-export { usePurchasingSidebar };
export * from "./PurchaseOrder";
export * from "./PurchaseOrders";
+export * from "./Supplier";
export * from "./Suppliers";
export * from "./SupplierTypes";
+export { usePurchasingSidebar };
diff --git a/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable/ContractorsTable.tsx b/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable/ContractorsTable.tsx
index 2295e72133..0a252bd148 100644
--- a/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable/ContractorsTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/Contractors/ContractorsTable/ContractorsTable.tsx
@@ -33,7 +33,7 @@ const ContractorsTable = memo(({ data, count }: ContractorsTableProps) => {
<Link
onClick={() => {
- navigate(`/x/purchasing/suppliers/${row?.original.supplierId}`);
+ navigate(`/x/supplier/${row?.original.supplierId}`);
}}
>
{row.original.supplierName}
diff --git a/apps/carbon/app/modules/resources/ui/Partners/PartnersTable/PartnersTable.tsx b/apps/carbon/app/modules/resources/ui/Partners/PartnersTable/PartnersTable.tsx
index 7fecb2667e..6037cd8337 100644
--- a/apps/carbon/app/modules/resources/ui/Partners/PartnersTable/PartnersTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/Partners/PartnersTable/PartnersTable.tsx
@@ -33,7 +33,7 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
<Link
onClick={() => {
- navigate(`/x/purchasing/suppliers/${row?.original.supplierId}`);
+ navigate(`/x/supplier/${row?.original.supplierId}`);
}}
>
{row.original.supplierName}
@@ -71,7 +71,7 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
);
}}
>
- View Partner
+ Edit Partner
</MenuItem>
<MenuItem
isDisabled={!permissions.can("delete", "resources")}
diff --git a/apps/carbon/app/modules/resources/ui/People/PeopleTable/PeopleTable.tsx b/apps/carbon/app/modules/resources/ui/People/PeopleTable/PeopleTable.tsx
index 83e7c842e1..4739fac1a8 100644
--- a/apps/carbon/app/modules/resources/ui/People/PeopleTable/PeopleTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/People/PeopleTable/PeopleTable.tsx
@@ -193,7 +193,7 @@ const PeopleTable = memo(
)
}
>
- View Employee
+ Edit Employee
</MenuItem>
);
}
diff --git a/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx b/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx
index 7b005eb9c5..2355c2a746 100644
--- a/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/WorkCells/WorkCellTypesTable/WorkCellTypesTable.tsx
@@ -15,10 +15,10 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
import { BiAddToQueue } from "react-icons/bi";
import {
- BsPencilSquare,
+ BsFillCheckCircleFill,
BsListUl,
+ BsPencilSquare,
BsPlus,
- BsFillCheckCircleFill,
} from "react-icons/bs";
import { IoMdTrash } from "react-icons/io";
import { Table } from "~/components";
@@ -150,7 +150,7 @@ const WorkCellTypesTable = memo(({ data, count }: WorkCellTypesTableProps) => {
);
}}
>
- View Work Cell
+ Edit Work Cell
</MenuItem>
<MenuItem
icon={<BsPencilSquare />}
diff --git a/apps/carbon/app/modules/sales/services/sales.form.ts b/apps/carbon/app/modules/sales/services/sales.form.ts
index f2ac4bc94c..a48048055d 100644
--- a/apps/carbon/app/modules/sales/services/sales.form.ts
+++ b/apps/carbon/app/modules/sales/services/sales.form.ts
@@ -11,6 +11,10 @@ export const customerValidator = withZod(
customerStatusId: zfd.text(z.string().optional()),
taxId: zfd.text(z.string().optional()),
accountManagerId: zfd.text(z.string().optional()),
+ defaultCurrencyCode: zfd.text(z.string().optional()),
+ defaultPaymentTermId: zfd.text(z.string().optional()),
+ defaultShippingTermId: zfd.text(z.string().optional()),
+ defaultShippingMethodId: zfd.text(z.string().optional()),
})
);
diff --git a/apps/carbon/app/modules/sales/services/sales.server.ts b/apps/carbon/app/modules/sales/services/sales.server.ts
index 8a4a04fb42..7f66ef3b96 100644
--- a/apps/carbon/app/modules/sales/services/sales.server.ts
+++ b/apps/carbon/app/modules/sales/services/sales.server.ts
@@ -41,49 +41,56 @@ export async function deleteCustomerType(
export async function getCustomer(
client: SupabaseClient<Database>,
customerId: string
+) {
+ return client.from("customer").select("*").eq("id", customerId).single();
+}
+
+export async function getCustomerContact(
+ client: SupabaseClient<Database>,
+ customerContactId: string
) {
return client
- .from("customer")
+ .from("customerContact")
.select(
- "id, name, customerTypeId, customerStatusId, taxId, accountManagerId"
+ "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes)"
)
- .eq("id", customerId)
+ .eq("id", customerContactId)
.single();
}
-export async function getCustomerLocations(
+export async function getCustomerContacts(
client: SupabaseClient<Database>,
customerId: string
) {
return client
- .from("customerLocation")
+ .from("customerContact")
.select(
- "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
+ "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes), user(id, active)"
)
.eq("customerId", customerId);
}
-export async function getCustomerContact(
+export async function getCustomerLocation(
client: SupabaseClient<Database>,
customerContactId: string
) {
return client
- .from("customerContact")
+ .from("customerLocation")
.select(
- "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes)"
+ "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
)
.eq("id", customerContactId)
.single();
}
-export async function getCustomerContacts(
+export async function getCustomerLocations(
client: SupabaseClient<Database>,
customerId: string
) {
return client
- .from("customerContact")
+ .from("customerLocation")
.select(
- "id, contact(id, firstName, lastName, email, mobilePhone, homePhone, workPhone, fax, title, addressLine1, addressLine2, city, state, postalCode, country(id, name), birthday, notes), user(id, active)"
+ "id, address(id, addressLine1, addressLine2, city, state, country(id, name), postalCode)"
)
.eq("customerId", customerId);
}
@@ -96,11 +103,9 @@ export async function getCustomers(
status: string | null;
}
) {
- let query = client
- .from("customer")
- .select("id, name, customerType(name), customerStatus(name)", {
- count: "exact",
- });
+ let query = client.from("customers_view").select("*", {
+ count: "exact",
+ });
if (args.name) {
query = query.ilike("name", `%${args.name}%`);
@@ -177,9 +182,14 @@ export async function getCustomerTypesList(client: SupabaseClient<Database>) {
export async function insertCustomer(
client: SupabaseClient<Database>,
- customer: TypeOfValidator<typeof customerValidator> & {
- createdBy: string;
- }
+ customer:
+ | (Omit<TypeOfValidator<typeof customerValidator>, "id"> & {
+ createdBy: string;
+ })
+ | (Omit<TypeOfValidator<typeof customerValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ })
) {
return client.from("customer").insert([customer]).select("id").single();
}
@@ -209,7 +219,7 @@ export async function insertCustomerContact(
}
) {
// Need to use service role here because it violates RLS
- // to select a contact that does not belong to any supplier
+ // to select a contact that does not belong to any customer
const insertContact = await getSupabaseServiceRole()
.from("contact")
.insert([customerContact.contact])
diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.ts
index 2fc0a7bdcd..b93a081a2d 100644
--- a/apps/carbon/app/modules/sales/types.ts
+++ b/apps/carbon/app/modules/sales/types.ts
@@ -1,4 +1,5 @@
import type {
+ getCustomer,
getCustomerContacts,
getCustomerLocations,
getCustomers,
@@ -14,6 +15,10 @@ export type CustomerContact = NonNullable<
Awaited<ReturnType<typeof getCustomerContacts>>["data"]
>[number];
+export type CustomerDetail = NonNullable<
+ Awaited<ReturnType<typeof getCustomer>>["data"]
+>;
+
export type CustomerLocation = NonNullable<
Awaited<ReturnType<typeof getCustomerLocations>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerContactsForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerContactForm/CustomerContactForm.tsx
similarity index 62%
rename from apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerContactsForm.tsx
rename to apps/carbon/app/modules/sales/ui/Customer/CustomerContactForm/CustomerContactForm.tsx
index 0823ca7efe..9b0acfaf9b 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerContactsForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerContactForm/CustomerContactForm.tsx
@@ -10,7 +10,7 @@ import {
HStack,
VStack,
} from "@chakra-ui/react";
-import { useParams } from "@remix-run/react";
+import { useNavigate, useParams } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
import {
DatePicker,
@@ -21,28 +21,23 @@ import {
TextArea,
} from "~/components/Form";
import { usePermissions } from "~/hooks";
-import type { CustomerContact, CustomerLocation } from "~/modules/sales";
import { customerContactValidator } from "~/modules/sales";
+import type { TypeOfValidator } from "~/types/validators";
type CustomerContactFormProps = {
- contact?: CustomerContact;
- locations?: CustomerLocation[];
- onClose: () => void;
+ initialValues: TypeOfValidator<typeof customerContactValidator>;
};
-const CustomerContactForm = ({
- contact,
- onClose,
-}: CustomerContactFormProps) => {
+const CustomerContactForm = ({ initialValues }: CustomerContactFormProps) => {
+ const navigate = useNavigate();
const { customerId } = useParams();
const permissions = usePermissions();
- const isEditing = !!contact?.id;
+ const isEditing = !!initialValues?.id;
const isDisabled = isEditing
- ? !permissions.can("update", "purchasing")
- : !permissions.can("create", "purchasing");
+ ? !permissions.can("update", "sales")
+ : !permissions.can("create", "sales");
- if (Array.isArray(contact?.contact))
- throw new Error("contact.contact is an array");
+ const onClose = () => navigate(`/x/customer/${customerId}/contacts`);
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
@@ -51,27 +46,10 @@ const CustomerContactForm = ({
method="post"
action={
isEditing
- ? `/x/sales/customers/${customerId}/contact/${contact?.id}`
- : `/x/sales/customers/${customerId}/contact/new`
+ ? `/x/customer/${customerId}/contacts/${initialValues?.id}`
+ : `/x/customer/${customerId}/contacts/new`
}
- defaultValues={{
- id: contact?.id ?? undefined,
- contactId: contact?.contact?.id ?? undefined,
- firstName: contact?.contact?.firstName ?? "",
- lastName: contact?.contact?.lastName ?? "",
- email: contact?.contact?.email ?? "",
- title: contact?.contact?.title ?? "",
- mobilePhone: contact?.contact?.mobilePhone ?? "",
- homePhone: contact?.contact?.homePhone ?? "",
- workPhone: contact?.contact?.workPhone ?? "",
- fax: contact?.contact?.fax ?? "",
- addressLine1: contact?.contact?.addressLine1 ?? "",
- addressLine2: contact?.contact?.addressLine2 ?? "",
- city: contact?.contact?.city ?? "",
- state: contact?.contact?.state ?? "",
- postalCode: contact?.contact?.postalCode ?? "",
- birthday: contact?.contact?.birthday ?? undefined,
- }}
+ defaultValues={initialValues}
onSubmit={onClose}
>
<DrawerOverlay />
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerContactForm/index.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerContactForm/index.tsx
new file mode 100644
index 0000000000..9da6f144fc
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerContactForm/index.tsx
@@ -0,0 +1,3 @@
+import CustomerContactForm from "./CustomerContactForm";
+
+export default CustomerContactForm;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerContacts/CustomerContacts.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerContacts/CustomerContacts.tsx
new file mode 100644
index 0000000000..5e6f0a3b97
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerContacts/CustomerContacts.tsx
@@ -0,0 +1,134 @@
+import {
+ Box,
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ List,
+ ListItem,
+ Text,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { Link, Outlet, useNavigate, useParams } from "@remix-run/react";
+import { useCallback, useState } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdAdd, IoMdTrash } from "react-icons/io";
+import { Contact } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import type { CustomerContact } from "~/modules/sales/types";
+
+type CustomerContactsProps = {
+ contacts: CustomerContact[];
+};
+
+const CustomerContacts = ({ contacts }: CustomerContactsProps) => {
+ const navigate = useNavigate();
+ const { customerId } = useParams();
+ if (!customerId) throw new Error("customerId is required");
+ const permissions = usePermissions();
+ const canEdit = permissions.can("create", "sales");
+ const isEmpty = contacts === undefined || contacts?.length === 0;
+
+ const deleteContactModal = useDisclosure();
+ const [contact, setSelectedContact] = useState<CustomerContact>();
+
+ const getActions = useCallback(
+ (contact: CustomerContact) => {
+ const actions = [];
+
+ actions.push({
+ label: permissions.can("update", "sales")
+ ? "Edit Contact"
+ : "View Contact",
+ icon: <BsPencilSquare />,
+ onClick: () => {
+ navigate(contact.id);
+ },
+ });
+
+ if (permissions.can("delete", "sales")) {
+ actions.push({
+ label: "Delete Contact",
+ icon: <IoMdTrash />,
+ onClick: () => {
+ setSelectedContact(contact);
+ deleteContactModal.onOpen();
+ },
+ });
+ }
+
+ if (permissions.can("create", "users") && contact.user === null) {
+ actions.push({
+ label: "Create Account",
+ icon: <IoMdAdd />,
+ onClick: () => {
+ navigate(
+ `/x/users/customers/new?id=${contact.id}&customer=${customerId}`
+ );
+ },
+ });
+ }
+
+ return actions;
+ },
+ [permissions, deleteContactModal, navigate, customerId]
+ );
+
+ return (
+ <>
+ <Card w="full">
+ <CardHeader display="flex" justifyContent="space-between">
+ <Heading size="md" display="inline-flex">
+ Contacts
+ </Heading>
+ {canEdit && (
+ <Button colorScheme="brand" as={Link} to="new">
+ New
+ </Button>
+ )}
+ </CardHeader>
+ <CardBody>
+ {isEmpty ? (
+ <Box w="full" my={8} textAlign="center">
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any contacts yet.
+ </Text>
+ </Box>
+ ) : (
+ <List w="full" spacing={4}>
+ {contacts?.map((contact) => (
+ <ListItem key={contact.id}>
+ {contact.contact &&
+ !Array.isArray(contact.contact) &&
+ !Array.isArray(contact.user) ? (
+ <Contact
+ contact={contact.contact}
+ url={`/x/customer/${customerId}/contacts/${contact.id}`}
+ user={contact.user}
+ actions={getActions(contact)}
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ </CardBody>
+ </Card>
+
+ <ConfirmDelete
+ action={`/x/customer/${customerId}/contacts/delete/${contact?.id}`}
+ isOpen={deleteContactModal.isOpen}
+ name={`${contact?.contact?.firstName} ${contact?.contact?.lastName}`}
+ text="Are you sure you want to delete this contact?"
+ onCancel={deleteContactModal.onClose}
+ onSubmit={deleteContactModal.onClose}
+ />
+
+ <Outlet />
+ </>
+ );
+};
+
+export default CustomerContacts;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerContacts/index.ts b/apps/carbon/app/modules/sales/ui/Customer/CustomerContacts/index.ts
new file mode 100644
index 0000000000..4ca1bc15e6
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerContacts/index.ts
@@ -0,0 +1,3 @@
+import CustomerContacts from "./CustomerContacts";
+
+export default CustomerContacts;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/CustomerForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/CustomerForm.tsx
new file mode 100644
index 0000000000..3dbf3a7e21
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/CustomerForm.tsx
@@ -0,0 +1,177 @@
+import {
+ Button,
+ Card,
+ CardBody,
+ CardFooter,
+ CardHeader,
+ Grid,
+ Heading,
+ HStack,
+ Text,
+ VStack,
+} from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import { ValidatedForm } from "remix-validated-form";
+import {
+ Currency,
+ Employee,
+ Hidden,
+ Input,
+ Select,
+ Submit,
+} from "~/components/Form";
+import { usePermissions, useRouteData } from "~/hooks";
+import type { CustomerStatus, CustomerType } from "~/modules/sales";
+import { customerValidator } from "~/modules/sales";
+import type { ListItem } from "~/types";
+import type { TypeOfValidator } from "~/types/validators";
+
+type CustomerFormProps = {
+ initialValues: TypeOfValidator<typeof customerValidator>;
+};
+
+const CustomerForm = ({ initialValues }: CustomerFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate("/x/sales/customers");
+
+ const routeData = useRouteData<{
+ customerTypes: CustomerType[];
+ customerStatuses: CustomerStatus[];
+ paymentTerms: ListItem[];
+ shippingMethods: ListItem[];
+ shippingTerms: ListItem[];
+ }>("/x/customer");
+
+ const customerTypeOptions =
+ routeData?.customerTypes?.map((type) => ({
+ value: type.id,
+ label: type.name,
+ })) ?? [];
+
+ const customerStatusOptions =
+ routeData?.customerStatuses?.map((status) => ({
+ value: status.id,
+ label: status.name,
+ })) ?? [];
+
+ const paymentTermOptions =
+ routeData?.paymentTerms?.map((term) => ({
+ value: term.id,
+ label: term.name,
+ })) ?? [];
+
+ const shippingMethodOptions =
+ routeData?.shippingMethods?.map((method) => ({
+ value: method.id,
+ label: method.name,
+ })) ?? [];
+
+ const shippingTermOptions =
+ routeData?.shippingTerms?.map((term) => ({
+ value: term.id,
+ label: term.name,
+ })) ?? [];
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "sales")
+ : !permissions.can("create", "sales");
+
+ return (
+ <ValidatedForm
+ method="post"
+ validator={customerValidator}
+ defaultValues={initialValues}
+ >
+ <Card w="full">
+ <CardHeader>
+ <Heading size="md">
+ {isEditing ? "Customer Basics" : "New Customer"}
+ </Heading>
+ {!isEditing && (
+ <Text color="gray.500">
+ A customer is a business or person who buys your parts or
+ services.
+ </Text>
+ )}
+ </CardHeader>
+ <CardBody>
+ <Hidden name="id" />
+ <Grid
+ gridTemplateColumns={
+ isEditing ? ["1fr", "1fr", "1fr 1fr 1fr"] : "1fr"
+ }
+ gridColumnGap={8}
+ gridRowGap={2}
+ w="full"
+ >
+ <VStack alignItems="start" spacing={2} w="full">
+ <Input name="name" label="Name" />
+ <Input name="taxId" label="Tax ID" />
+ <Select
+ name="customerTypeId"
+ label="Customer Type"
+ options={customerTypeOptions}
+ placeholder="Select Customer Type"
+ />
+ </VStack>
+ {isEditing && (
+ <>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Employee name="accountManagerId" label="Account Manager" />
+ <Select
+ name="customerStatusId"
+ label="Customer Status"
+ options={customerStatusOptions}
+ placeholder="Select Customer Status"
+ />
+ <Currency
+ name="defaultCurrencyCode"
+ label="Currency"
+ placeholder="Default Currency"
+ />
+ </VStack>
+ <VStack alignItems="start" spacing={2} w="full">
+ <Select
+ name="defaultPaymentTermId"
+ label="Payment Term"
+ options={paymentTermOptions}
+ placeholder="Default Payment Term"
+ />
+ <Select
+ name="defaultShippingMethodId"
+ label="Shipping Method"
+ options={shippingMethodOptions}
+ placeholder="Default Shipping Method"
+ />
+ <Select
+ name="defaultShippingTermId"
+ label="Shipping Term"
+ options={shippingTermOptions}
+ placeholder="Default Shipping Term"
+ />
+ </VStack>
+ </>
+ )}
+ </Grid>
+ </CardBody>
+ <CardFooter>
+ <HStack spacing={2}>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </CardFooter>
+ </Card>
+ </ValidatedForm>
+ );
+};
+
+export default CustomerForm;
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/index.ts b/apps/carbon/app/modules/sales/ui/Customer/CustomerForm/index.ts
similarity index 100%
rename from apps/carbon/app/modules/sales/ui/Customers/CustomerForm/index.ts
rename to apps/carbon/app/modules/sales/ui/Customer/CustomerForm/index.ts
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader/CustomerHeader.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader/CustomerHeader.tsx
new file mode 100644
index 0000000000..b5f20beab1
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader/CustomerHeader.tsx
@@ -0,0 +1,94 @@
+import {
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ HStack,
+ Stack,
+ Text,
+ VStack,
+} from "@chakra-ui/react";
+import { useParams } from "@remix-run/react";
+import { FaHistory } from "react-icons/fa";
+import { useRouteData } from "~/hooks";
+import type {
+ CustomerDetail,
+ CustomerStatus,
+ CustomerType,
+} from "~/modules/sales";
+import type { ListItem } from "~/types";
+
+const CustomerHeader = () => {
+ const { customerId } = useParams();
+ if (!customerId) throw new Error("Could not find customerId");
+ const routeData = useRouteData<{ customer: CustomerDetail }>(
+ `/x/customer/${customerId}`
+ );
+ const sharedCustomerData = useRouteData<{
+ customerTypes: CustomerType[];
+ customerStatuses: CustomerStatus[];
+ paymentTerms: ListItem[];
+ }>("/x/customer");
+
+ return (
+ <VStack w="full" alignItems="start" spacing={2}>
+ <Card w="full">
+ <CardHeader>
+ <HStack justifyContent="space-between" alignItems="start">
+ <Stack direction="column" spacing={2}>
+ <Heading size="md">{routeData?.customer?.name}</Heading>
+ </Stack>
+ <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
+ Customer Details
+ </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">Type</Text>
+ <Text fontWeight="bold">
+ {sharedCustomerData?.customerTypes?.find(
+ (type) => type.id === routeData?.customer?.customerTypeId
+ )?.name ?? "--"}
+ </Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Status</Text>
+ <Text fontWeight="bold">
+ {sharedCustomerData?.customerStatuses?.find(
+ (status) =>
+ status.id === routeData?.customer?.customerStatusId
+ )?.name ?? "--"}
+ </Text>
+ </Stack>
+ <Stack
+ direction={["row", "row", "column"]}
+ alignItems="start"
+ justifyContent="space-between"
+ >
+ <Text color="gray.500">Payment Terms</Text>
+ <Text fontWeight="bold">
+ {sharedCustomerData?.paymentTerms?.find(
+ (term) =>
+ term.id === routeData?.customer?.defaultPaymentTermId
+ )?.name ?? "--"}
+ </Text>
+ </Stack>
+ </Stack>
+ </CardBody>
+ </Card>
+ </VStack>
+ );
+};
+
+export default CustomerHeader;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader/index.ts b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader/index.ts
new file mode 100644
index 0000000000..0569b423a7
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerHeader/index.ts
@@ -0,0 +1,3 @@
+import CustomerHeader from "./CustomerHeader";
+
+export default CustomerHeader;
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerLocationForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm/CustomerLocationForm.tsx
similarity index 68%
rename from apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerLocationForm.tsx
rename to apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm/CustomerLocationForm.tsx
index 2c4c986153..2edeaa31e2 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerLocationForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm/CustomerLocationForm.tsx
@@ -10,31 +10,27 @@ import {
HStack,
VStack,
} from "@chakra-ui/react";
-import { useParams } from "@remix-run/react";
+import { useNavigate, useParams } from "@remix-run/react";
import { ValidatedForm } from "remix-validated-form";
import { Hidden, Input, Submit } from "~/components/Form";
import { usePermissions } from "~/hooks";
-import type { CustomerLocation } from "~/modules/sales";
import { customerLocationValidator } from "~/modules/sales";
+import type { TypeOfValidator } from "~/types/validators";
type CustomerLocationFormProps = {
- location?: CustomerLocation;
- onClose: () => void;
+ initialValues: TypeOfValidator<typeof customerLocationValidator>;
};
-const CustomerLocationForm = ({
- location,
- onClose,
-}: CustomerLocationFormProps) => {
+const CustomerLocationForm = ({ initialValues }: CustomerLocationFormProps) => {
+ const navigate = useNavigate();
const { customerId } = useParams();
const permissions = usePermissions();
- const isEditing = !!location?.id;
+ const isEditing = !!initialValues?.id;
const isDisabled = isEditing
? !permissions.can("update", "sales")
: !permissions.can("create", "sales");
- if (Array.isArray(location?.address))
- throw new Error("location.address is an array");
+ const onClose = () => navigate(`/x/customer/${customerId}/locations`);
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
@@ -43,19 +39,10 @@ const CustomerLocationForm = ({
method="post"
action={
isEditing
- ? `/x/sales/customers/${customerId}/location/${location?.id}`
- : `/x/sales/customers/${customerId}/location/new`
+ ? `/x/customer/${customerId}/locations/${initialValues?.id}`
+ : `/x/customer/${customerId}/locations/new`
}
- defaultValues={{
- id: location?.id ?? undefined,
- addressId: location?.address?.id ?? undefined,
-
- addressLine1: location?.address?.addressLine1 ?? "",
- addressLine2: location?.address?.addressLine2 ?? "",
- city: location?.address?.city ?? "",
- state: location?.address?.state ?? "",
- postalCode: location?.address?.postalCode ?? "",
- }}
+ defaultValues={initialValues}
onSubmit={onClose}
>
<DrawerOverlay />
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm/index.ts b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm/index.ts
new file mode 100644
index 0000000000..35df58bce6
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocationForm/index.ts
@@ -0,0 +1,3 @@
+import CustomerLocationForm from "./CustomerLocationForm";
+
+export default CustomerLocationForm;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerLocations/CustomerLocations.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocations/CustomerLocations.tsx
new file mode 100644
index 0000000000..f8ee8f372b
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocations/CustomerLocations.tsx
@@ -0,0 +1,118 @@
+import {
+ Box,
+ Button,
+ Card,
+ CardBody,
+ CardHeader,
+ Heading,
+ List,
+ ListItem,
+ Text,
+ useDisclosure,
+} from "@chakra-ui/react";
+import { Link, Outlet, useNavigate, useParams } from "@remix-run/react";
+import { useCallback, useState } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Address } from "~/components";
+import { ConfirmDelete } from "~/components/Modals";
+import { usePermissions } from "~/hooks";
+import type { CustomerLocation } from "~/modules/sales";
+
+type CustomerLocationsProps = {
+ locations: CustomerLocation[];
+};
+
+const CustomerLocations = ({ locations }: CustomerLocationsProps) => {
+ const navigate = useNavigate();
+ const { customerId } = useParams();
+ if (!customerId) throw new Error("customerId is required");
+ const permissions = usePermissions();
+ const canEdit = permissions.can("create", "sales");
+ const isEmpty = locations === undefined || locations?.length === 0;
+
+ const deleteLocationModal = useDisclosure();
+ const [location, setSelectedLocation] = useState<CustomerLocation>();
+
+ const getActions = useCallback(
+ (location: CustomerLocation) => {
+ const actions = [];
+ if (permissions.can("update", "sales")) {
+ actions.push({
+ label: "Edit Location",
+ icon: <BsPencilSquare />,
+ onClick: () => {
+ navigate(location.id);
+ },
+ });
+ }
+ if (permissions.can("delete", "sales")) {
+ actions.push({
+ label: "Delete Location",
+ icon: <IoMdTrash />,
+ onClick: () => {
+ setSelectedLocation(location);
+ deleteLocationModal.onOpen();
+ },
+ });
+ }
+
+ return actions;
+ },
+ [permissions, deleteLocationModal, navigate]
+ );
+
+ return (
+ <>
+ <Card w="full">
+ <CardHeader display="flex" justifyContent="space-between">
+ <Heading size="md" display="inline-flex">
+ Locations
+ </Heading>
+ {canEdit && (
+ <Button colorScheme="brand" as={Link} to="new">
+ New
+ </Button>
+ )}
+ </CardHeader>
+ <CardBody>
+ {isEmpty ? (
+ <Box w="full" my={8} textAlign="center">
+ <Text color="gray.500" fontSize="sm">
+ You haven’t created any locations yet.
+ </Text>
+ </Box>
+ ) : (
+ <List w="full" spacing={4}>
+ {locations?.map((location) => (
+ <ListItem key={location.id}>
+ {location.address && !Array.isArray(location.address) ? (
+ <Address
+ address={location.address}
+ actions={getActions(location)}
+ />
+ ) : null}
+ </ListItem>
+ ))}
+ </List>
+ )}
+ </CardBody>
+ </Card>
+
+ {deleteLocationModal.isOpen && (
+ <ConfirmDelete
+ action={`/x/customer/${customerId}/locations/delete/${location?.id}`}
+ // @ts-ignore
+ name={location?.address?.city ?? ""}
+ text="Are you sure you want to delete this location?"
+ onCancel={deleteLocationModal.onClose}
+ onSubmit={deleteLocationModal.onClose}
+ />
+ )}
+
+ <Outlet />
+ </>
+ );
+};
+
+export default CustomerLocations;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerLocations/index.ts b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocations/index.ts
new file mode 100644
index 0000000000..90bffd6e65
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerLocations/index.ts
@@ -0,0 +1,3 @@
+import CustomerLocations from "./CustomerLocations";
+
+export default CustomerLocations;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/CustomerSidebar.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/CustomerSidebar.tsx
new file mode 100644
index 0000000000..c11beea4f2
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/CustomerSidebar.tsx
@@ -0,0 +1,70 @@
+import { Count, useColor } from "@carbon/react";
+import { Box, Button, VStack } from "@chakra-ui/react";
+import { Link, useMatches, useParams } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type {
+ CustomerContact,
+ CustomerDetail,
+ CustomerLocation,
+} from "~/modules/sales";
+import { useCustomerSidebar } from "./useCustomerSidebar";
+
+const CustomerSidebar = () => {
+ const { customerId } = useParams();
+ const borderColor = useColor("gray.200");
+ if (!customerId)
+ throw new Error(
+ "CustomerSidebar requires an customerId and could not find customerId in params"
+ );
+
+ const routeData = useRouteData<{
+ purchaseOrder: CustomerDetail;
+ contacts: CustomerContact[];
+ locations: CustomerLocation[];
+ }>(`/x/customer/${customerId}`);
+ const links = useCustomerSidebar({
+ contacts: routeData?.contacts.length ?? 0,
+ locations: routeData?.locations.length ?? 0,
+ });
+ 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={isActive ? "1px solid" : "none"}
+ borderColor={borderColor}
+ fontWeight={isActive ? "bold" : "normal"}
+ justifyContent={
+ route.count === undefined ? "start" : "space-between"
+ }
+ size="md"
+ w="full"
+ >
+ <span>{route.name}</span>
+ {route.count !== undefined && <Count count={route.count} />}
+ </Button>
+ );
+ })}
+ </VStack>
+ </VStack>
+ </Box>
+ </VStack>
+ );
+};
+
+export default CustomerSidebar;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/index.ts b/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/index.ts
new file mode 100644
index 0000000000..d0e56cc265
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/index.ts
@@ -0,0 +1,3 @@
+import CustomerSidebar from "./CustomerSidebar";
+
+export default CustomerSidebar;
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/useCustomerSidebar.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/useCustomerSidebar.tsx
new file mode 100644
index 0000000000..da331338c2
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerSidebar/useCustomerSidebar.tsx
@@ -0,0 +1,33 @@
+import { usePermissions } from "~/hooks";
+import type { Role } from "~/types";
+
+type Props = {
+ contacts: number;
+ locations: number;
+};
+
+export function useCustomerSidebar({ contacts, locations }: Props) {
+ const permissions = usePermissions();
+ return [
+ {
+ name: "Summary",
+ to: "",
+ },
+ {
+ name: "Contacts",
+ to: "contacts",
+ role: ["employee"],
+ count: contacts,
+ },
+ {
+ name: "Locations",
+ to: "locations",
+ role: ["employee", "customer"],
+ count: locations,
+ },
+ ].filter(
+ (item) =>
+ item.role === undefined ||
+ item.role.some((role) => permissions.is(role as Role))
+ );
+}
diff --git a/apps/carbon/app/modules/sales/ui/Customer/index.ts b/apps/carbon/app/modules/sales/ui/Customer/index.ts
new file mode 100644
index 0000000000..85c8b03340
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Customer/index.ts
@@ -0,0 +1,17 @@
+import CustomerContactForm from "./CustomerContactForm";
+import CustomerContacts from "./CustomerContacts";
+import CustomerForm from "./CustomerForm";
+import CustomerHeader from "./CustomerHeader";
+import CustomerLocationForm from "./CustomerLocationForm";
+import CustomerLocations from "./CustomerLocations";
+import CustomerSidebar from "./CustomerSidebar";
+
+export {
+ CustomerContactForm,
+ CustomerContacts,
+ CustomerForm,
+ CustomerHeader,
+ CustomerLocationForm,
+ CustomerLocations,
+ CustomerSidebar,
+};
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/CustomerForm.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/CustomerForm.tsx
deleted file mode 100644
index b71b3431c7..0000000000
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/CustomerForm.tsx
+++ /dev/null
@@ -1,149 +0,0 @@
-import {
- Box,
- Button,
- Drawer,
- DrawerBody,
- DrawerCloseButton,
- DrawerContent,
- DrawerFooter,
- DrawerHeader,
- DrawerOverlay,
- Grid,
- HStack,
- VStack,
-} from "@chakra-ui/react";
-import { useNavigate } from "@remix-run/react";
-import { ValidatedForm } from "remix-validated-form";
-import { Employee, Hidden, Input, Select, Submit } from "~/components/Form";
-import { usePermissions, useRouteData } from "~/hooks";
-import type {
- CustomerContact,
- CustomerLocation,
- CustomerStatus,
- CustomerType,
-} from "~/modules/sales";
-import { customerValidator } from "~/modules/sales";
-import type { TypeOfValidator } from "~/types/validators";
-import { CustomerContacts, CustomerLocations } from "./components";
-
-type CustomerFormProps = {
- initialValues: TypeOfValidator<typeof customerValidator>;
- contacts?: CustomerContact[];
- locations?: CustomerLocation[];
-};
-
-const CustomerForm = ({
- initialValues,
- contacts,
- locations,
-}: CustomerFormProps) => {
- const permissions = usePermissions();
- const navigate = useNavigate();
- const onClose = () => navigate("/x/sales/customers");
-
- const routeData = useRouteData<{
- customerTypes: CustomerType[];
- customerStatuses: CustomerStatus[];
- }>("/x/sales/customers");
-
- const customerTypeOptions =
- routeData?.customerTypes?.map((type) => ({
- value: type.id,
- label: type.name,
- })) ?? [];
-
- const customerStatusOptions =
- routeData?.customerStatuses?.map((status) => ({
- value: status.id,
- label: status.name,
- })) ?? [];
-
- const isEditing = initialValues.id !== undefined;
- const isDisabled = isEditing
- ? !permissions.can("update", "purchasing")
- : !permissions.can("create", "purchasing");
-
- return (
- <Drawer onClose={onClose} isOpen size="full">
- <ValidatedForm
- method="post"
- action={
- isEditing
- ? `/x/sales/customers/${initialValues.id}`
- : "/x/sales/customers/new"
- }
- validator={customerValidator}
- defaultValues={initialValues}
- >
- <DrawerOverlay />
- <DrawerContent>
- <DrawerCloseButton />
- <DrawerHeader>
- {isEditing ? initialValues.name : "New Customer"}
- </DrawerHeader>
- <DrawerBody>
- <Grid
- gridTemplateColumns={["1fr", "1fr", "5fr 2fr"]}
- gridColumnGap={8}
- w="full"
- >
- <Box w="full">
- <Hidden name="id" />
- <VStack spacing={4} w="full" alignItems="start">
- <Grid
- gridTemplateColumns={["1fr", "1fr", "1fr 1fr"]}
- gridColumnGap={8}
- gridRowGap={4}
- w="full"
- >
- <Input name="name" label="Name" />
- <Input name="taxId" label="Tax ID" />
- <Select
- name="customerTypeId"
- label="Customer Type"
- options={customerTypeOptions}
- placeholder="Select Customer Type"
- />
- <Employee name="accountManagerId" label="Account Manager" />
- <Select
- name="customerStatusId"
- label="Customer Status"
- options={customerStatusOptions}
- placeholder="Select Customer Status"
- />
- </Grid>
- </VStack>
- </Box>
- <VStack spacing={8} w="full" alignItems="start" py={[8, 8, 0]}>
- <CustomerLocations
- locations={locations}
- isEditing={isEditing}
- />
- <CustomerContacts
- contacts={contacts}
- locations={locations}
- isEditing={isEditing}
- />
- </VStack>
- </Grid>
- </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 CustomerForm;
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerContacts.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerContacts.tsx
deleted file mode 100644
index de3f0737c5..0000000000
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerContacts.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import {
- Button,
- HStack,
- Heading,
- IconButton,
- List,
- ListItem,
- Text,
- VStack,
- useDisclosure,
-} from "@chakra-ui/react";
-import { useNavigate, useParams } from "@remix-run/react";
-import { useCallback, useState } from "react";
-import { IoMdAdd, IoMdTrash } from "react-icons/io";
-import { Contact } from "~/components";
-import { ConfirmDelete } from "~/components/Modals";
-import type { CustomerContact, CustomerLocation } from "~/modules/sales";
-import { usePermissions } from "~/hooks";
-import CustomerContactForm from "./CustomerContactsForm";
-import { BsPencilSquare } from "react-icons/bs";
-
-type CustomerContactProps = {
- contacts?: CustomerContact[];
- locations?: CustomerLocation[];
- isEditing?: boolean;
-};
-
-const CustomerContacts = ({
- contacts = [],
- locations = [],
- isEditing = false,
-}: CustomerContactProps) => {
- const { customerId } = useParams();
- const navigate = useNavigate();
- const permissions = usePermissions();
-
- const [contact, setContact] = useState<CustomerContact | undefined>(
- undefined
- );
-
- const contactDrawer = useDisclosure();
- const deleteContactModal = useDisclosure();
-
- const isEmpty = contacts === undefined || contacts?.length === 0;
-
- const getActions = useCallback(
- (contact: CustomerContact) => {
- const actions = [];
- if (permissions.can("update", "sales")) {
- actions.push({
- label: "Edit Contact",
- icon: <BsPencilSquare />,
- onClick: () => {
- setContact(contact);
- contactDrawer.onOpen();
- },
- });
- }
- if (permissions.can("delete", "sales")) {
- actions.push({
- label: "Delete Contact",
- icon: <IoMdTrash />,
- onClick: () => {
- setContact(contact);
- deleteContactModal.onOpen();
- },
- });
- }
-
- if (permissions.can("create", "users") && contact.user === null) {
- actions.push({
- label: "Create Account",
- icon: <IoMdAdd />,
- onClick: () => {
- navigate(
- `/x/users/customers/new?id=${contact.id}&customer=${customerId}`
- );
- },
- });
- }
-
- return actions;
- },
- [permissions, customerId, contactDrawer, deleteContactModal, navigate]
- );
-
- return (
- <>
- <VStack alignItems="start" w="full" spacing={4} mb={4}>
- <HStack w="full" justifyContent="space-between">
- <Heading size="md">Contacts</Heading>
- {permissions.can("create", "sales") && (
- <IconButton
- icon={<IoMdAdd />}
- aria-label="Add contact"
- variant="outline"
- onClick={() => {
- setContact(undefined);
- contactDrawer.onOpen();
- }}
- />
- )}
- </HStack>
- {isEmpty && (
- <Text color="gray.500" fontSize="sm">
- You haven’t created any contacts yet.
- </Text>
- )}
- {!isEmpty && (
- <List w="full" spacing={4}>
- {contacts?.map((contact) => (
- <ListItem key={contact.id}>
- {contact.contact &&
- !Array.isArray(contact.contact) &&
- !Array.isArray(contact.user) ? (
- <Contact
- contact={contact.contact}
- user={contact.user}
- actions={getActions(contact)}
- />
- ) : null}
- </ListItem>
- ))}
- </List>
- )}
- {isEmpty && permissions.can("create", "sales") && (
- <Button
- leftIcon={<IoMdAdd />}
- colorScheme="brand"
- onClick={() => {
- setContact(undefined);
- contactDrawer.onOpen();
- }}
- isDisabled={!isEditing}
- >
- New Contact
- </Button>
- )}
- </VStack>
- {contactDrawer.isOpen && (
- <CustomerContactForm
- onClose={contactDrawer.onClose}
- contact={contact}
- locations={locations}
- />
- )}
- {deleteContactModal.isOpen && (
- <ConfirmDelete
- action={`/x/sales/customers/${customerId}/contact/delete/${contact?.id}`}
- // @ts-ignore
- name={`${contact?.contact.firstName} ${contact?.contact.lastName}`}
- text="Are you sure you want to delete this contact?"
- onCancel={deleteContactModal.onClose}
- onSubmit={deleteContactModal.onClose}
- />
- )}
- </>
- );
-};
-
-export default CustomerContacts;
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerLocations.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerLocations.tsx
deleted file mode 100644
index 55679fca94..0000000000
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/CustomerLocations.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import {
- Button,
- Heading,
- HStack,
- IconButton,
- List,
- ListItem,
- Text,
- VStack,
- useDisclosure,
-} from "@chakra-ui/react";
-import { useParams } from "@remix-run/react";
-import { useCallback, useState } from "react";
-import { BsPencilSquare } from "react-icons/bs";
-import { IoMdAdd, IoMdTrash } from "react-icons/io";
-import { Address } from "~/components";
-import { ConfirmDelete } from "~/components/Modals";
-import { usePermissions } from "~/hooks";
-import type { CustomerLocation } from "~/modules/sales";
-import CustomerLocationForm from "./CustomerLocationForm";
-
-type CustomerLocationProps = {
- locations?: CustomerLocation[];
- isEditing?: boolean;
-};
-
-const CustomerLocations = ({
- locations = [],
- isEditing = false,
-}: CustomerLocationProps) => {
- const permissions = usePermissions();
- const locationDrawer = useDisclosure();
- const deleteContactModal = useDisclosure();
-
- const { customerId } = useParams();
-
- const [location, setLocation] = useState<CustomerLocation | undefined>(
- undefined
- );
-
- const isEmpty = locations === undefined || locations?.length === 0;
-
- const getActions = useCallback(
- (location: CustomerLocation) => {
- const actions = [];
- if (permissions.can("update", "purchasing")) {
- actions.push({
- label: "Edit Location",
- icon: <BsPencilSquare />,
- onClick: () => {
- setLocation(location);
- locationDrawer.onOpen();
- },
- });
- }
- if (permissions.can("delete", "purchasing")) {
- actions.push({
- label: "Delete Location",
- icon: <IoMdTrash />,
- onClick: () => {
- setLocation(location);
- deleteContactModal.onOpen();
- },
- });
- }
- return actions;
- },
- [permissions, locationDrawer, deleteContactModal]
- );
-
- return (
- <>
- <VStack alignItems="start" w="full" spacing={4} mb={4}>
- <HStack w="full" justifyContent="space-between">
- <Heading size="md">Locations</Heading>
- {permissions.can("create", "sales") && (
- <IconButton
- icon={<IoMdAdd />}
- aria-label="Add location"
- variant="outline"
- onClick={() => {
- setLocation(undefined);
- locationDrawer.onOpen();
- }}
- />
- )}
- </HStack>
- {isEmpty && (
- <Text color="gray.500" fontSize="sm">
- You haven’t created any locations yet.
- </Text>
- )}
- {!isEmpty && (
- <List w="full" spacing={4}>
- {locations?.map((location) => (
- <ListItem key={location.id}>
- {location.address && !Array.isArray(location.address) ? (
- <Address
- address={location.address}
- actions={getActions(location)}
- />
- ) : null}
- </ListItem>
- ))}
- </List>
- )}
- {isEmpty && permissions.can("create", "sales") && (
- <Button
- leftIcon={<IoMdAdd />}
- colorScheme="brand"
- onClick={() => {
- setLocation(undefined);
- locationDrawer.onOpen();
- }}
- isDisabled={!isEditing}
- >
- New Location
- </Button>
- )}
- </VStack>
- {locationDrawer.isOpen && (
- <CustomerLocationForm
- onClose={locationDrawer.onClose}
- location={location}
- />
- )}
- {deleteContactModal.isOpen && (
- <ConfirmDelete
- action={`/x/sales/customers/${customerId}/location/delete/${location?.id}`}
- // @ts-ignore
- name={location?.address?.city ?? ""}
- text="Are you sure you want to delete this location?"
- onCancel={deleteContactModal.onClose}
- onSubmit={deleteContactModal.onClose}
- />
- )}
- </>
- );
-};
-
-export default CustomerLocations;
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/index.ts b/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/index.ts
deleted file mode 100644
index a298cd1300..0000000000
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomerForm/components/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import CustomerContacts from "./CustomerContacts";
-import CustomerLocations from "./CustomerLocations";
-
-export { CustomerContacts, CustomerLocations };
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable/CustomersTable.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable/CustomersTable.tsx
index 7ecb2fd5d6..adad1a9b84 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable/CustomersTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable/CustomersTable.tsx
@@ -1,16 +1,9 @@
-import {
- Button,
- ButtonGroup,
- IconButton,
- Link,
- MenuItem,
-} from "@chakra-ui/react";
+import { Link, MenuItem } from "@chakra-ui/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
-import { BsPencilSquare, BsPlus } from "react-icons/bs";
+import { BsPencilSquare } from "react-icons/bs";
import { Table } from "~/components";
-import { useUrlParams } from "~/hooks";
import type { Customer } from "~/modules/sales";
type CustomersTableProps = {
@@ -20,7 +13,6 @@ type CustomersTableProps = {
const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
const navigate = useNavigate();
- const [params] = useUrlParams();
const columns = useMemo<ColumnDef<Customer>[]>(() => {
return [
@@ -28,61 +20,43 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
accessorKey: "name",
header: "Name",
cell: ({ row }) => (
- <Link onClick={() => navigate(row.original.id)}>
+ <Link onClick={() => navigate(`/x/customer/${row.original.id}`)}>
{row.original.name}
</Link>
),
},
{
- // @ts-ignore
- accessorFn: (item) => item.customerType?.name ?? "",
+ accessorKey: "type",
header: "Customer Type",
cell: (item) => item.getValue(),
},
{
- // @ts-ignore
- accessorFn: (item) => item.customerStatus?.name ?? "",
+ accessorKey: "status",
header: "Customer Status",
cell: (item) => item.getValue(),
},
- {
- id: "orders",
- header: "Orders",
- cell: () => (
- <ButtonGroup
- size="sm"
- isAttached
- variant="outline"
- onClick={(e) => e.stopPropagation()}
- >
- <Button onClick={() => console.log("orders")}>0 Orders</Button>
- <IconButton
- aria-label="New Order"
- icon={<BsPlus />}
- onClick={() => console.log("new order")}
- />
- </ButtonGroup>
- ),
- },
- {
- id: "parts",
- header: "Parts",
- cell: () => (
- <ButtonGroup
- size="sm"
- isAttached
- variant="outline"
- onClick={(e) => e.stopPropagation()}
- >
- <Button onClick={() => console.log("orders")}>0 Parts</Button>
- <IconButton
- aria-label="New Part"
- icon={<BsPlus />}
- onClick={() => console.log("new part")}
- />
- </ButtonGroup>
- ),
- },
+ // {
+ // id: "orders",
+ // header: "Orders",
+ // cell: ({ row }) => (
+ // <ButtonGroup size="sm" isAttached variant="outline">
+ // <Button
+ // onClick={() =>
+ // navigate(`/x/sales/orders?customerId=${row.original.id}`)
+ // }
+ // >
+ // {row.original.orderCount ?? 0} Orders
+ // </Button>
+ // <IconButton
+ // aria-label="New Order"
+ // icon={<BsPlus />}
+ // onClick={() =>
+ // navigate(`/x/purchase-order/new?customerId=${row.original.id}`)
+ // }
+ // />
+ // </ButtonGroup>
+ // ),
+ // },
];
}, [navigate]);
@@ -92,14 +66,12 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
(
<MenuItem
icon={<BsPencilSquare />}
- onClick={() =>
- navigate(`/x/sales/customers/${row.id}?${params.toString()}`)
- }
+ onClick={() => navigate(`/x/sales/customers/${row.id}`)}
>
- View Customer
+ Edit Customer
</MenuItem>
),
- [navigate, params]
+ [navigate]
);
return (
@@ -108,8 +80,8 @@ const CustomersTable = memo(({ data, count }: CustomersTableProps) => {
count={count}
columns={columns}
data={data}
- renderContextMenu={renderContextMenu}
withPagination
+ renderContextMenu={renderContextMenu}
/>
</>
);
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomersTableFilters/CustomersTableFilters.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomersTableFilters/CustomersTableFilters.tsx
index 6cab7a58a7..efbe16cbb9 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomersTableFilters/CustomersTableFilters.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customers/CustomersTableFilters/CustomersTableFilters.tsx
@@ -83,7 +83,7 @@ const CustomersTableFilters = ({
{permissions.can("create", "sales") && (
<Button
as={Link}
- to={`new?${params.toString()}`}
+ to={`/x/customer/new?${params.toString()}`}
colorScheme="brand"
leftIcon={<IoMdAdd />}
>
diff --git a/apps/carbon/app/modules/sales/ui/Customers/index.ts b/apps/carbon/app/modules/sales/ui/Customers/index.ts
index e56992acd2..bfc2c47c3e 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/index.ts
+++ b/apps/carbon/app/modules/sales/ui/Customers/index.ts
@@ -1,5 +1,4 @@
-import CustomerForm from "./CustomerForm";
import CustomersTable from "./CustomersTable";
import CustomersTableFilters from "./CustomersTableFilters";
-export { CustomerForm, CustomersTable, CustomersTableFilters };
+export { CustomersTable, CustomersTableFilters };
diff --git a/apps/carbon/app/modules/sales/ui/index.ts b/apps/carbon/app/modules/sales/ui/index.ts
index 7aa3f90ada..d08664ba75 100644
--- a/apps/carbon/app/modules/sales/ui/index.ts
+++ b/apps/carbon/app/modules/sales/ui/index.ts
@@ -1,5 +1,5 @@
import useSalesSidebar from "./useSalesSidebar";
-
-export { useSalesSidebar };
-export * from "./CustomerTypes";
+export * from "./Customer";
export * from "./Customers";
+export * from "./CustomerTypes";
+export { useSalesSidebar };
diff --git a/apps/carbon/app/modules/users/ui/Customers/CustomerAccountsTable/CustomerAccountsTable.tsx b/apps/carbon/app/modules/users/ui/Customers/CustomerAccountsTable/CustomerAccountsTable.tsx
index f7da18afb4..b7d1b3492c 100644
--- a/apps/carbon/app/modules/users/ui/Customers/CustomerAccountsTable/CustomerAccountsTable.tsx
+++ b/apps/carbon/app/modules/users/ui/Customers/CustomerAccountsTable/CustomerAccountsTable.tsx
@@ -7,7 +7,7 @@ import { IoMdTrash } from "react-icons/io";
import { Avatar, Table } from "~/components";
import { usePermissions } from "~/hooks";
import type { Customer } from "~/modules/users";
-import { ResendInviteModal, DeactivateUsersModal } from "~/modules/users";
+import { DeactivateUsersModal, ResendInviteModal } from "~/modules/users";
type CustomerAccountsTableProps = {
data: Customer[];
@@ -94,8 +94,8 @@ const CustomerAccountsTable = memo(
{
header: "Customer Type",
cell: ({ row }) => {
- // @ts-ignore
const customerType = row.original.customer?.customerType;
+ // @ts-ignore
return customerType ? customerType.name : "";
},
},
diff --git a/apps/carbon/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx b/apps/carbon/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx
index c5cc529b7a..b8c0da46a9 100644
--- a/apps/carbon/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx
+++ b/apps/carbon/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx
@@ -7,7 +7,7 @@ import { IoMdTrash } from "react-icons/io";
import { Avatar, Table } from "~/components";
import { usePermissions } from "~/hooks";
import type { Supplier } from "~/modules/users";
-import { ResendInviteModal, DeactivateUsersModal } from "~/modules/users";
+import { DeactivateUsersModal, ResendInviteModal } from "~/modules/users";
type SupplierAccountsTableProps = {
data: Supplier[];
@@ -94,8 +94,8 @@ const SupplierAccountsTable = memo(
{
header: "Supplier Type",
cell: ({ row }) => {
- // @ts-ignore
const supplierType = row.original.supplier?.supplierType;
+ // @ts-ignore
return supplierType ? supplierType.name : "";
},
},
diff --git a/apps/carbon/app/root.tsx b/apps/carbon/app/root.tsx
index 5ce9738fa2..5cb8de0688 100644
--- a/apps/carbon/app/root.tsx
+++ b/apps/carbon/app/root.tsx
@@ -15,6 +15,7 @@ import {
useLoaderData,
useRouteError,
} from "@remix-run/react";
+import { Analytics } from "@vercel/analytics/react";
import React from "react";
import { getBrowserEnv } from "~/config/env";
import Background from "~/styles/background.css";
@@ -68,8 +69,8 @@ function Document({
<body>
{children}
<ScrollRestoration />
-
<Scripts />
+ <Analytics />
{process.env.NODE_ENV === "development" && <LiveReload />}
</body>
</html>
diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.contacts.$customerContactId.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.$customerContactId.tsx
new file mode 100644
index 0000000000..a4d68ce861
--- /dev/null
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.$customerContactId.tsx
@@ -0,0 +1,111 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import {
+ CustomerContactForm,
+ customerContactValidator,
+ getCustomerContact,
+ updateCustomerContact,
+} from "~/modules/sales";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { customerId, customerContactId } = params;
+ if (!customerId) throw notFound("customerId not found");
+ if (!customerContactId) throw notFound("customerContactId not found");
+
+ const contact = await getCustomerContact(client, customerContactId);
+ if (contact.error) {
+ return redirect(
+ `/x/customer/${customerId}/contacts`,
+ await flash(
+ request,
+ error(contact.error, "Failed to get customer contact")
+ )
+ );
+ }
+
+ return json({
+ contact: contact.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { customerId, customerContactId } = params;
+ if (!customerId) throw notFound("customerId not found");
+ if (!customerContactId) throw notFound("customerContactId not found");
+
+ const validation = await customerContactValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, contactId, ...contact } = validation.data;
+
+ if (id !== customerContactId)
+ throw badRequest("customerContactId does not match id from form data");
+
+ if (contactId === undefined)
+ throw badRequest("contactId is undefined from form data");
+
+ const update = await updateCustomerContact(client, {
+ contactId,
+ contact,
+ });
+
+ if (update.error) {
+ return redirect(
+ `/x/customer/${customerId}/contacts`,
+ await flash(
+ request,
+ error(update.error, "Failed to update customer contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/x/customer/${customerId}/contacts`,
+ await flash(request, success("Customer contact updated"))
+ );
+}
+
+export default function EditCustomerContactRoute() {
+ const { contact } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: contact?.id ?? undefined,
+ contactId: contact?.contact?.id ?? undefined,
+ firstName: contact?.contact?.firstName ?? "",
+ lastName: contact?.contact?.lastName ?? "",
+ email: contact?.contact?.email ?? "",
+ title: contact?.contact?.title ?? "",
+ mobilePhone: contact?.contact?.mobilePhone ?? "",
+ homePhone: contact?.contact?.homePhone ?? "",
+ workPhone: contact?.contact?.workPhone ?? "",
+ fax: contact?.contact?.fax ?? "",
+ addressLine1: contact?.contact?.addressLine1 ?? "",
+ addressLine2: contact?.contact?.addressLine2 ?? "",
+ city: contact?.contact?.city ?? "",
+ state: contact?.contact?.state ?? "",
+ postalCode: contact?.contact?.postalCode ?? "",
+ birthday: contact?.contact?.birthday ?? undefined,
+ };
+
+ return <CustomerContactForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.delete.$customerContactId.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.delete.$customerContactId.tsx
similarity index 87%
rename from apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.delete.$customerContactId.tsx
rename to apps/carbon/app/routes/x+/customer+/$customerId.contacts.delete.$customerContactId.tsx
index 0eeb04f4ad..4a61c73976 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.delete.$customerContactId.tsx
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.delete.$customerContactId.tsx
@@ -18,6 +18,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // TODO: check whether this person has an account or is a partner first
+
const { error: deleteCustomerContactError } = await deleteCustomerContact(
client,
customerId,
@@ -25,7 +27,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
if (deleteCustomerContactError) {
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/contacts`,
await flash(
request,
error(deleteCustomerContactError, "Failed to delete customer contact")
@@ -34,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/contacts`,
await flash(request, success("Successfully deleted customer contact"))
);
}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.new.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx
similarity index 81%
rename from apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.new.tsx
rename to apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx
index a10acbc9a5..5f1ce0c9a4 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.new.tsx
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.new.tsx
@@ -2,6 +2,7 @@ import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import {
+ CustomerContactForm,
customerContactValidator,
insertCustomerContact,
} from "~/modules/sales";
@@ -35,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
if (createCustomerContact.error) {
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/contacts`,
await flash(
request,
error(createCustomerContact.error, "Failed to create customer contact")
@@ -44,7 +45,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/contacts`,
await flash(request, success("Customer contact created"))
);
}
+
+export default function CustomerContactsNewRoute() {
+ const initialValues = {
+ firstName: "",
+ lastName: "",
+ email: "",
+ };
+
+ return <CustomerContactForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.contacts.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.tsx
new file mode 100644
index 0000000000..48f4204f35
--- /dev/null
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.contacts.tsx
@@ -0,0 +1,37 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { CustomerContacts, getCustomerContacts } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { customerId } = params;
+ if (!customerId) throw new Error("Could not find customerId");
+
+ const contacts = await getCustomerContacts(client, customerId);
+ if (contacts.error) {
+ return redirect(
+ `/x/customer/${customerId}`,
+ await flash(
+ request,
+ error(contacts.error, "Failed to fetch customer contacts")
+ )
+ );
+ }
+
+ return json({
+ contacts: contacts.data ?? [],
+ });
+}
+
+export default function CustomerContactsRoute() {
+ const { contacts } = useLoaderData<typeof loader>();
+
+ return <CustomerContacts contacts={contacts} />;
+}
diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.index.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.index.tsx
new file mode 100644
index 0000000000..4cacb19491
--- /dev/null
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.index.tsx
@@ -0,0 +1,79 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useParams } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { useRouteData } from "~/hooks";
+import type { CustomerDetail } from "~/modules/sales";
+import {
+ CustomerForm,
+ customerValidator,
+ updateCustomer,
+} from "~/modules/sales";
+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 }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const validation = await customerValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ if (!id) {
+ return redirect(
+ "/x/sales/customers",
+ await flash(request, error(null, "Failed to update customer"))
+ );
+ }
+
+ const update = await updateCustomer(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ return redirect(
+ "/x/sales/customers",
+ await flash(request, error(update.error, "Failed to update customer"))
+ );
+ }
+
+ return json(null, await flash(request, success("Updated customer")));
+}
+
+export default function CustomerEditRoute() {
+ const { customerId } = useParams();
+ if (!customerId) throw new Error("Could not find customerId");
+ const routeData = useRouteData<{ customer: CustomerDetail }>(
+ `/x/customer/${customerId}`
+ );
+
+ if (!routeData?.customer) return null;
+
+ const initialValues = {
+ id: routeData?.customer?.id ?? undefined,
+ name: routeData?.customer?.name ?? "",
+ customerTypeId: routeData?.customer?.customerTypeId ?? undefined,
+ customerStatusId: routeData?.customer?.customerStatusId ?? undefined,
+ accountManagerId: routeData?.customer?.accountManagerId ?? undefined,
+ taxId: routeData?.customer?.taxId ?? "",
+ defaultCurrencyCode: routeData?.customer?.defaultCurrencyCode ?? "",
+ defaultPaymentTermId:
+ routeData?.customer?.defaultPaymentTermId ?? undefined,
+ defaultShippingMethodId:
+ routeData?.customer?.defaultShippingMethodId ?? undefined,
+ defaultShippingTermId:
+ routeData?.customer?.defaultShippingTermId ?? undefined,
+ };
+
+ return <CustomerForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.locations.$customerLocationId.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.locations.$customerLocationId.tsx
new file mode 100644
index 0000000000..586542b18f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.locations.$customerLocationId.tsx
@@ -0,0 +1,99 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import {
+ CustomerLocationForm,
+ customerLocationValidator,
+ getCustomerLocation,
+ updateCustomerLocation,
+} from "~/modules/sales";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { customerId, customerLocationId } = params;
+ if (!customerId) throw notFound("customerId not found");
+ if (!customerLocationId) throw notFound("customerLocationId not found");
+
+ const location = await getCustomerLocation(client, customerLocationId);
+ if (location.error) {
+ return redirect(
+ `/x/customer/${customerId}/locations`,
+ await flash(
+ request,
+ error(location.error, "Failed to get customer location")
+ )
+ );
+ }
+
+ return json({
+ location: location.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { customerId, customerLocationId } = params;
+ if (!customerId) throw notFound("customerId not found");
+ if (!customerLocationId) throw notFound("customerLocationId not found");
+
+ const validation = await customerLocationValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, addressId, ...address } = validation.data;
+
+ if (addressId === undefined)
+ throw badRequest("addressId is undefined in form data");
+
+ const update = await updateCustomerLocation(client, {
+ addressId,
+ address,
+ });
+ if (update.error) {
+ return redirect(
+ `/x/customer/${customerId}/locations`,
+ await flash(
+ request,
+ error(update.error, "Failed to update customer address")
+ )
+ );
+ }
+
+ return redirect(
+ `/x/customer/${customerId}/locations`,
+ await flash(request, success("Customer address updated"))
+ );
+}
+
+export default function EditCustomerLocationRoute() {
+ const { location } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: location?.id ?? undefined,
+ addressId: location?.address?.id ?? undefined,
+
+ addressLine1: location?.address?.addressLine1 ?? "",
+ addressLine2: location?.address?.addressLine2 ?? "",
+ city: location?.address?.city ?? "",
+ state: location?.address?.state ?? "",
+ postalCode: location?.address?.postalCode ?? "",
+ };
+
+ return <CustomerLocationForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.location.delete.$customerLocationId.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx
similarity index 92%
rename from apps/carbon/app/routes/x+/sales+/customers.$customerId.location.delete.$customerLocationId.tsx
rename to apps/carbon/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx
index 2564c6c37d..42ef401bf0 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.location.delete.$customerLocationId.tsx
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx
@@ -28,7 +28,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
if (deleteCustomerLocationError) {
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/locations`,
await flash(
request,
error(deleteCustomerLocationError, "Failed to delete customer location")
@@ -37,7 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/locations`,
await flash(request, success("Successfully deleted customer location"))
);
}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.location.new.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.locations.new.tsx
similarity index 84%
rename from apps/carbon/app/routes/x+/sales+/customers.$customerId.location.new.tsx
rename to apps/carbon/app/routes/x+/customer+/$customerId.locations.new.tsx
index 4aa50cbe34..6a5c9ad3af 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.location.new.tsx
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.locations.new.tsx
@@ -2,6 +2,7 @@ import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import {
+ CustomerLocationForm,
customerLocationValidator,
insertCustomerLocation,
} from "~/modules/sales";
@@ -35,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
if (createCustomerLocation.error) {
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/locations`,
await flash(
request,
error(
@@ -47,7 +48,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}/locations`,
await flash(request, success("Customer location created"))
);
}
+
+export default function CustomerLocationsNewRoute() {
+ const initialValues = {};
+
+ return <CustomerLocationForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.locations.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.locations.tsx
new file mode 100644
index 0000000000..a506ab2469
--- /dev/null
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.locations.tsx
@@ -0,0 +1,37 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { CustomerLocations, getCustomerLocations } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { customerId } = params;
+ if (!customerId) throw new Error("Could not find customerId");
+
+ const locations = await getCustomerLocations(client, customerId);
+ if (locations.error) {
+ return redirect(
+ `/x/customer/${customerId}`,
+ await flash(
+ request,
+ error(locations.error, "Failed to fetch customer locations")
+ )
+ );
+ }
+
+ return json({
+ locations: locations.data ?? [],
+ });
+}
+
+export default function CustomerLocationsRoute() {
+ const { locations } = useLoaderData<typeof loader>();
+
+ return <CustomerLocations locations={locations} />;
+}
diff --git a/apps/carbon/app/routes/x+/customer+/$customerId.tsx b/apps/carbon/app/routes/x+/customer+/$customerId.tsx
new file mode 100644
index 0000000000..d467b8e242
--- /dev/null
+++ b/apps/carbon/app/routes/x+/customer+/$customerId.tsx
@@ -0,0 +1,61 @@
+import { Grid } from "@chakra-ui/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import {
+ CustomerHeader,
+ CustomerSidebar,
+ getCustomer,
+ getCustomerContacts,
+ getCustomerLocations,
+} from "~/modules/sales";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { customerId } = params;
+ if (!customerId) throw new Error("Could not find customerId");
+
+ const [customer, contacts, locations] = await Promise.all([
+ getCustomer(client, customerId),
+ getCustomerContacts(client, customerId),
+ getCustomerLocations(client, customerId),
+ ]);
+
+ if (customer.error) {
+ return redirect(
+ "/x/sales/customers",
+ await flash(
+ request,
+ error(customer.error, "Failed to load customer summary")
+ )
+ );
+ }
+
+ return json({
+ customer: customer.data,
+ contacts: contacts.data ?? [],
+ locations: locations.data ?? [],
+ });
+}
+
+export default function CustomerRoute() {
+ return (
+ <>
+ <CustomerHeader />
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 4fr"]}
+ gridColumnGap={4}
+ w="full"
+ >
+ <CustomerSidebar />
+ <Outlet />
+ </Grid>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/customer+/_layout.tsx b/apps/carbon/app/routes/x+/customer+/_layout.tsx
new file mode 100644
index 0000000000..6109f451c3
--- /dev/null
+++ b/apps/carbon/app/routes/x+/customer+/_layout.tsx
@@ -0,0 +1,50 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { getPaymentTermsList } from "~/modules/accounting";
+import {
+ getShippingMethodsList,
+ getShippingTermsList,
+} from "~/modules/inventory";
+import { getCustomerStatuses, getCustomerTypes } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Part" }];
+};
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const [
+ customerTypes,
+ customerStatuses,
+ paymentTerms,
+ shippingMethods,
+ shippingTerms,
+ ] = await Promise.all([
+ getCustomerTypes(client),
+ getCustomerStatuses(client),
+ getPaymentTermsList(client),
+ getShippingMethodsList(client),
+ getShippingTermsList(client),
+ ]);
+
+ return json({
+ customerStatuses: customerStatuses.data ?? [],
+ customerTypes: customerTypes.data ?? [],
+ paymentTerms: paymentTerms.data ?? [],
+ shippingMethods: shippingMethods.data ?? [],
+ shippingTerms: shippingTerms.data ?? [],
+ });
+}
+
+export default function CustomerRoute() {
+ return (
+ <VStack w="full" h="full" spacing={4} p={4}>
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.new.tsx b/apps/carbon/app/routes/x+/customer+/new.tsx
similarity index 97%
rename from apps/carbon/app/routes/x+/sales+/customers.new.tsx
rename to apps/carbon/app/routes/x+/customer+/new.tsx
index db26d2a91f..60bfa1fbb0 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.new.tsx
+++ b/apps/carbon/app/routes/x+/customer+/new.tsx
@@ -42,7 +42,7 @@ export async function action({ request }: ActionFunctionArgs) {
const customerId = createCustomer.data?.id;
return redirect(
- `/x/sales/customers/${customerId}`,
+ `/x/customer/${customerId}`,
await flash(request, success("Created customer"))
);
}
diff --git a/apps/carbon/app/routes/x+/part+/$partId.index.tsx b/apps/carbon/app/routes/x+/part+/$partId.index.tsx
index 7f4029b23e..db5297b4d2 100644
--- a/apps/carbon/app/routes/x+/part+/$partId.index.tsx
+++ b/apps/carbon/app/routes/x+/part+/$partId.index.tsx
@@ -3,13 +3,7 @@ import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { validationError } from "remix-validated-form";
import { useRouteData } from "~/hooks";
-import type {
- PartGroupListItem,
- PartReplenishmentSystem,
- PartSummary,
- PartType,
- UnitOfMeasureListItem,
-} from "~/modules/parts";
+import type { PartSummary } from "~/modules/parts";
import { PartForm, partValidator, upsertPart } from "~/modules/parts";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
@@ -51,13 +45,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function PartBasicRoute() {
- const sharedPartsData = useRouteData<{
- partGroups: PartGroupListItem[];
- partTypes: PartType[];
- partReplenishmentSystems: PartReplenishmentSystem[];
- unitOfMeasures: UnitOfMeasureListItem[];
- }>("/x/part");
-
const { partId } = useParams();
const partData = useRouteData<{ partSummary: PartSummary }>(
`/x/part/${partId}`
@@ -76,13 +63,5 @@ export default function PartBasicRoute() {
active: partData.partSummary?.active,
};
- return (
- <PartForm
- initialValues={initialValues}
- partGroups={sharedPartsData?.partGroups ?? []}
- partTypes={sharedPartsData?.partTypes ?? []}
- partReplenishmentSystems={sharedPartsData?.partReplenishmentSystems ?? []}
- unitOfMeasures={sharedPartsData?.unitOfMeasures ?? []}
- />
- );
+ return <PartForm initialValues={initialValues} />;
}
diff --git a/apps/carbon/app/routes/x+/part+/_layout.tsx b/apps/carbon/app/routes/x+/part+/_layout.tsx
index a9a1bd46f2..bc4e6e523b 100644
--- a/apps/carbon/app/routes/x+/part+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/part+/_layout.tsx
@@ -14,7 +14,7 @@ import { getLocationsList } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
export const meta: MetaFunction = () => {
- return [{ title: "Carbon | Login" }];
+ return [{ title: "Carbon | Part" }];
};
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/carbon/app/routes/x+/part+/new.tsx b/apps/carbon/app/routes/x+/part+/new.tsx
index 81f96a882e..dc8cdad845 100644
--- a/apps/carbon/app/routes/x+/part+/new.tsx
+++ b/apps/carbon/app/routes/x+/part+/new.tsx
@@ -2,13 +2,6 @@ import { Box } from "@chakra-ui/react";
import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
-import { useRouteData } from "~/hooks";
-import type {
- PartGroupListItem,
- PartReplenishmentSystem,
- PartType,
- UnitOfMeasureListItem,
-} from "~/modules/parts";
import { PartForm, partValidator, upsertPart } from "~/modules/parts";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
@@ -48,13 +41,6 @@ export async function action({ request }: ActionFunctionArgs) {
}
export default function PartsNewRoute() {
- const routeData = useRouteData<{
- partGroups: PartGroupListItem[];
- partTypes: PartType[];
- partReplenishmentSystems: PartReplenishmentSystem[];
- unitOfMeasures: UnitOfMeasureListItem[];
- }>("/x/part");
-
const initialValues = {
name: "",
description: "",
@@ -65,13 +51,7 @@ export default function PartsNewRoute() {
return (
<Box w="50%" maxW={720} minW={420}>
- <PartForm
- initialValues={initialValues}
- partGroups={routeData?.partGroups ?? []}
- partTypes={routeData?.partTypes ?? []}
- partReplenishmentSystems={routeData?.partReplenishmentSystems ?? []}
- unitOfMeasures={routeData?.unitOfMeasures ?? []}
- />
+ <PartForm initialValues={initialValues} />
</Box>
);
}
diff --git a/apps/carbon/app/routes/x+/purchasing+/orders.tsx b/apps/carbon/app/routes/x+/purchasing+/orders.tsx
index 000d81412f..da3a05251a 100644
--- a/apps/carbon/app/routes/x+/purchasing+/orders.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/orders.tsx
@@ -4,7 +4,6 @@ import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData } from "@remix-run/react";
import {
getPurchaseOrders,
- getPurchaseOrderSuppliers,
PurchaseOrdersTable,
PurchaseOrdersTableFilters,
} from "~/modules/purchasing";
@@ -27,7 +26,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [purchasOrders, suppliers] = await Promise.all([
+ const [purchasOrders] = await Promise.all([
getPurchaseOrders(client, {
search,
status,
@@ -37,7 +36,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
sorts,
filters,
}),
- getPurchaseOrderSuppliers(client),
]);
if (purchasOrders.error) {
@@ -53,16 +51,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
return json({
count: purchasOrders.count ?? 0,
purchasOrders: purchasOrders.data ?? [],
- suppliers: suppliers.data ?? [],
});
}
export default function PurchaseOrdersSearchRoute() {
- const { count, purchasOrders, suppliers } = useLoaderData<typeof loader>();
+ const { count, purchasOrders } = useLoaderData<typeof loader>();
return (
<VStack w="full" h="full" spacing={0}>
- <PurchaseOrdersTableFilters suppliers={suppliers} />
+ <PurchaseOrdersTableFilters />
<PurchaseOrdersTable data={purchasOrders} count={count} />
<Outlet />
</VStack>
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.$supplierContactId.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.$supplierContactId.tsx
deleted file mode 100644
index 9c7c51e9a5..0000000000
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.$supplierContactId.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import type { ActionFunctionArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import { validationError } from "remix-validated-form";
-import {
- supplierContactValidator,
- updateSupplierContact,
-} from "~/modules/purchasing";
-import { requirePermissions } from "~/services/auth";
-import { flash } from "~/services/session";
-import { assertIsPost, badRequest, notFound } from "~/utils/http";
-import { error, success } from "~/utils/result";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {});
-
- const { supplierId, supplierContactId } = params;
- if (!supplierId) throw notFound("supplierId not found");
- if (!supplierContactId) throw notFound("supplierContactId not found");
-
- const validation = await supplierContactValidator.validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, contactId, ...contact } = validation.data;
-
- if (id !== supplierContactId)
- throw badRequest("supplierContactId does not match id from form data");
-
- if (contactId === undefined)
- throw badRequest("contactId is undefined from form data");
-
- const update = await updateSupplierContact(client, {
- contactId,
- contact,
- });
-
- if (update.error) {
- return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
- await flash(
- request,
- error(update.error, "Failed to update supplier contact")
- )
- );
- }
-
- return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
- await flash(request, success("Supplier contact updated"))
- );
-}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.$supplierLocationId.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.$supplierLocationId.tsx
deleted file mode 100644
index 84d55eea07..0000000000
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.$supplierLocationId.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import type { ActionFunctionArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import { validationError } from "remix-validated-form";
-import {
- supplierLocationValidator,
- updateSupplierLocation,
-} from "~/modules/purchasing";
-import { requirePermissions } from "~/services/auth";
-import { flash } from "~/services/session";
-import { assertIsPost, badRequest, notFound } from "~/utils/http";
-import { error, success } from "~/utils/result";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- update: "purchasing",
- });
-
- const { supplierId, supplierLocationId } = params;
- if (!supplierId) throw notFound("supplierId not found");
- if (!supplierLocationId) throw notFound("supplierLocationId not found");
-
- const validation = await supplierLocationValidator.validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, addressId, ...address } = validation.data;
-
- if (addressId === undefined)
- throw badRequest("addressId is undefined in form data");
-
- const update = await updateSupplierLocation(client, {
- addressId,
- address,
- });
- if (update.error) {
- return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
- await flash(
- request,
- error(update.error, "Failed to update supplier address")
- )
- );
- }
-
- return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
- await flash(request, success("Supplier address updated"))
- );
-}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.tsx
deleted file mode 100644
index 245a518935..0000000000
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
-import { json, redirect } from "@remix-run/node";
-import { useLoaderData } from "@remix-run/react";
-import { validationError } from "remix-validated-form";
-import {
- getSupplier,
- getSupplierContacts,
- getSupplierLocations,
- SupplierForm,
- supplierValidator,
- updateSupplier,
-} from "~/modules/purchasing";
-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 }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "purchasing",
- });
-
- const { supplierId } = params;
- if (!supplierId) throw notFound("supplierTypeId not found");
-
- const [supplier, contacts, locations] = await Promise.all([
- getSupplier(client, supplierId),
- getSupplierContacts(client, supplierId),
- getSupplierLocations(client, supplierId),
- ]);
- if (supplier.error)
- return redirect(
- "/x/purchasing/suppliers",
- await flash(request, error(supplier.error, "Failed to get supplier"))
- );
-
- if (contacts.error)
- return redirect(
- "/x/purchasing/suppliers",
- await flash(
- request,
- error(contacts.error, "Failed to get supplier contacts")
- )
- );
-
- if (locations.error)
- return redirect(
- "/x/purchasing/suppliers",
- await flash(
- request,
- error(locations.error, "Failed to get supplier locations")
- )
- );
-
- return json({
- supplier: supplier.data,
- contacts: contacts.data,
- locations: locations.data,
- });
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- create: "purchasing",
- });
-
- const validation = await supplierValidator.validate(await request.formData());
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, ...data } = validation.data;
-
- if (!id) {
- return redirect(
- "/x/purchasing/suppliers",
- await flash(request, error(null, "Failed to update supplier"))
- );
- }
-
- const update = await updateSupplier(client, {
- id,
- ...data,
- updatedBy: userId,
- });
- if (update.error) {
- return redirect(
- "/x/purchasing/suppliers",
- await flash(request, error(update.error, "Failed to update supplier"))
- );
- }
-
- return json(null, await flash(request, success("Updated supplier")));
-}
-
-export default function SupplierEditRoute() {
- const { supplier, contacts, locations } = useLoaderData<typeof loader>();
-
- const initialValues = {
- id: supplier.id ?? undefined,
- name: supplier.name ?? "",
- supplierTypeId: supplier.supplierTypeId ?? undefined,
- supplierStatusId: supplier.supplierStatusId ?? undefined,
- accountManagerId: supplier.accountManagerId ?? undefined,
- taxId: supplier.taxId ?? "",
- defaultCurrencyCode: supplier.defaultCurrencyCode ?? "",
- defaultPaymentTermId: supplier.defaultPaymentTermId ?? undefined,
- defaultShippingMethodId: supplier.defaultShippingMethodId ?? undefined,
- defaultShippingTermId: supplier.defaultShippingTermId ?? undefined,
- };
-
- return (
- <SupplierForm
- initialValues={initialValues}
- contacts={contacts ?? []}
- locations={locations ?? []}
- />
- );
-}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx b/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx
index dfb3403f76..daac0873b2 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx
+++ b/apps/carbon/app/routes/x+/purchasing+/suppliers.tsx
@@ -2,11 +2,6 @@ import { VStack } from "@chakra-ui/react";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData } from "@remix-run/react";
-import { getPaymentTermsList } from "~/modules/accounting";
-import {
- getShippingMethodsList,
- getShippingTermsList,
-} from "~/modules/inventory";
import {
getSuppliers,
getSupplierStatuses,
@@ -33,20 +28,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [
- suppliers,
- supplierTypes,
- supplierStatuses,
- paymentTerms,
- shippingMethods,
- shippingTerms,
- ] = await Promise.all([
+ const [suppliers, supplierTypes, supplierStatuses] = await Promise.all([
getSuppliers(client, { name, type, status, limit, offset, sorts, filters }),
getSupplierTypes(client),
getSupplierStatuses(client),
- getPaymentTermsList(client),
- getShippingMethodsList(client),
- getShippingTermsList(client),
]);
if (suppliers.error) {
@@ -61,9 +46,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
suppliers: suppliers.data ?? [],
supplierStatuses: supplierStatuses.data ?? [],
supplierTypes: supplierTypes.data ?? [],
- paymentTerms: paymentTerms.data ?? [],
- shippingMethods: shippingMethods.data ?? [],
- shippingTerms: shippingTerms.data ?? [],
});
}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.$customerContactId.tsx b/apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.$customerContactId.tsx
deleted file mode 100644
index 1270b3883a..0000000000
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.contact.$customerContactId.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-import type { ActionFunctionArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import { validationError } from "remix-validated-form";
-import {
- customerContactValidator,
- updateCustomerContact,
-} from "~/modules/sales";
-import { requirePermissions } from "~/services/auth";
-import { flash } from "~/services/session";
-import { assertIsPost, badRequest, notFound } from "~/utils/http";
-import { error, success } from "~/utils/result";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- update: "sales",
- });
-
- const { customerId, customerContactId } = params;
- if (!customerId) throw notFound("customerId not found");
- if (!customerContactId) throw notFound("customerContactId not found");
-
- const validation = await customerContactValidator.validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, contactId, ...contact } = validation.data;
-
- if (id !== customerContactId)
- throw badRequest("customerContactId does not match id from form data");
-
- if (contactId === undefined)
- throw badRequest("contactId is undefined from form data");
-
- const update = await updateCustomerContact(client, {
- contactId,
- contact,
- });
- if (update.error) {
- return redirect(
- `/x/sales/customers/${customerId}`,
- await flash(
- request,
- error(update.error, "Failed to update customer contact")
- )
- );
- }
-
- return redirect(
- `/x/sales/customers/${customerId}`,
- await flash(request, success("Customer contact updated"))
- );
-}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.location.$customerLocationId.tsx b/apps/carbon/app/routes/x+/sales+/customers.$customerId.location.$customerLocationId.tsx
deleted file mode 100644
index 7455fb96ff..0000000000
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.location.$customerLocationId.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import type { ActionFunctionArgs } from "@remix-run/node";
-import { redirect } from "@remix-run/node";
-import { validationError } from "remix-validated-form";
-import {
- customerLocationValidator,
- updateCustomerLocation,
-} from "~/modules/sales";
-import { requirePermissions } from "~/services/auth";
-import { flash } from "~/services/session";
-import { assertIsPost, badRequest, notFound } from "~/utils/http";
-import { error, success } from "~/utils/result";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client } = await requirePermissions(request, {
- update: "sales",
- });
-
- const { customerId, customerLocationId } = params;
- if (!customerId) throw notFound("customerId not found");
- if (!customerLocationId) throw notFound("customerLocationId not found");
-
- const validation = await customerLocationValidator.validate(
- await request.formData()
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, addressId, ...address } = validation.data;
-
- if (!addressId) throw badRequest("addressId is undefined in form data");
-
- const update = await updateCustomerLocation(client, {
- addressId,
- address,
- });
- if (update.error) {
- return redirect(
- `/x/sales/customers/${customerId}`,
- await flash(
- request,
- error(update.error, "Failed to update customer address")
- )
- );
- }
-
- return redirect(
- `/x/sales/customers/${customerId}`,
- await flash(request, success("Customer address updated"))
- );
-}
diff --git a/apps/carbon/app/routes/x+/sales+/customers.$customerId.tsx b/apps/carbon/app/routes/x+/sales+/customers.$customerId.tsx
deleted file mode 100644
index 0f41a8f570..0000000000
--- a/apps/carbon/app/routes/x+/sales+/customers.$customerId.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
-import { json, redirect } from "@remix-run/node";
-import { useLoaderData } from "@remix-run/react";
-import { validationError } from "remix-validated-form";
-import {
- CustomerForm,
- customerValidator,
- getCustomer,
- getCustomerContacts,
- getCustomerLocations,
- updateCustomer,
-} from "~/modules/sales";
-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 }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "sales",
- });
-
- const { customerId } = params;
- if (!customerId) throw notFound("customerTypeId not found");
-
- const [customer, contacts, locations] = await Promise.all([
- getCustomer(client, customerId),
- getCustomerContacts(client, customerId),
- getCustomerLocations(client, customerId),
- ]);
- if (customer.error)
- return redirect(
- "/x/sales/customers",
- await flash(request, error(customer.error, "Failed to get customer"))
- );
-
- if (contacts.error)
- return redirect(
- "/x/sales/customers",
- await flash(
- request,
- error(contacts.error, "Failed to get customer contacts")
- )
- );
-
- if (locations.error)
- return redirect(
- "/x/sales/customers",
- await flash(
- request,
- error(locations.error, "Failed to get customer locations")
- )
- );
-
- return json({
- customer: customer.data,
- contacts: contacts.data,
- locations: locations.data,
- });
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- create: "sales",
- });
-
- const validation = await customerValidator.validate(await request.formData());
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, ...data } = validation.data;
-
- if (!id) {
- return redirect(
- "/x/sales/customers",
- await flash(request, error(null, "Failed to update customer"))
- );
- }
-
- const update = await updateCustomer(client, {
- id,
- ...data,
- updatedBy: userId,
- });
- if (update.error) {
- return redirect(
- "/x/sales/customers",
- await flash(request, error(update.error, "Failed to update customer"))
- );
- }
-
- return json(null, await flash(request, success("Updated customer")));
-}
-
-export default function CustomersNewRoute() {
- const { customer, contacts, locations } = useLoaderData<typeof loader>();
-
- const initialValues = {
- id: customer.id ?? undefined,
- name: customer.name ?? "",
- customerTypeId: customer.customerTypeId ?? undefined,
- customerStatusId: customer.customerStatusId ?? undefined,
- accountManagerId: customer.accountManagerId ?? undefined,
- taxId: customer.taxId ?? "",
- };
-
- return (
- <CustomerForm
- initialValues={initialValues}
- contacts={contacts ?? []}
- locations={locations ?? []}
- />
- );
-}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.$supplierContactId.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.$supplierContactId.tsx
new file mode 100644
index 0000000000..3f33a3e7af
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.$supplierContactId.tsx
@@ -0,0 +1,111 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import {
+ getSupplierContact,
+ SupplierContactForm,
+ supplierContactValidator,
+ updateSupplierContact,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { supplierId, supplierContactId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+ if (!supplierContactId) throw notFound("supplierContactId not found");
+
+ const contact = await getSupplierContact(client, supplierContactId);
+ if (contact.error) {
+ return redirect(
+ `/x/supplier/${supplierId}/contacts`,
+ await flash(
+ request,
+ error(contact.error, "Failed to get supplier contact")
+ )
+ );
+ }
+
+ return json({
+ contact: contact.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { supplierId, supplierContactId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+ if (!supplierContactId) throw notFound("supplierContactId not found");
+
+ const validation = await supplierContactValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, contactId, ...contact } = validation.data;
+
+ if (id !== supplierContactId)
+ throw badRequest("supplierContactId does not match id from form data");
+
+ if (contactId === undefined)
+ throw badRequest("contactId is undefined from form data");
+
+ const update = await updateSupplierContact(client, {
+ contactId,
+ contact,
+ });
+
+ if (update.error) {
+ return redirect(
+ `/x/supplier/${supplierId}/contacts`,
+ await flash(
+ request,
+ error(update.error, "Failed to update supplier contact")
+ )
+ );
+ }
+
+ return redirect(
+ `/x/supplier/${supplierId}/contacts`,
+ await flash(request, success("Supplier contact updated"))
+ );
+}
+
+export default function EditSupplierContactRoute() {
+ const { contact } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: contact?.id ?? undefined,
+ contactId: contact?.contact?.id ?? undefined,
+ firstName: contact?.contact?.firstName ?? "",
+ lastName: contact?.contact?.lastName ?? "",
+ email: contact?.contact?.email ?? "",
+ title: contact?.contact?.title ?? "",
+ mobilePhone: contact?.contact?.mobilePhone ?? "",
+ homePhone: contact?.contact?.homePhone ?? "",
+ workPhone: contact?.contact?.workPhone ?? "",
+ fax: contact?.contact?.fax ?? "",
+ addressLine1: contact?.contact?.addressLine1 ?? "",
+ addressLine2: contact?.contact?.addressLine2 ?? "",
+ city: contact?.contact?.city ?? "",
+ state: contact?.contact?.state ?? "",
+ postalCode: contact?.contact?.postalCode ?? "",
+ birthday: contact?.contact?.birthday ?? undefined,
+ };
+
+ return <SupplierContactForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.delete.$supplierContactId.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.delete.$supplierContactId.tsx
similarity index 87%
rename from apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.delete.$supplierContactId.tsx
rename to apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.delete.$supplierContactId.tsx
index cddf3a00c2..d80a140217 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.delete.$supplierContactId.tsx
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.delete.$supplierContactId.tsx
@@ -18,6 +18,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // TODO: check whether this person has an account or is a partner first
+
const { error: deleteSupplierContactError } = await deleteSupplierContact(
client,
supplierId,
@@ -25,7 +27,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
if (deleteSupplierContactError) {
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/contacts`,
await flash(
request,
error(deleteSupplierContactError, "Failed to delete supplier contact")
@@ -34,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/contacts`,
await flash(request, success("Successfully deleted supplier contact"))
);
}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.new.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
similarity index 81%
rename from apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.new.tsx
rename to apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
index 64bdc9ab3c..2c9d0af1d7 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.contact.new.tsx
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.new.tsx
@@ -3,6 +3,7 @@ import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import {
insertSupplierContact,
+ SupplierContactForm,
supplierContactValidator,
} from "~/modules/purchasing";
import { requirePermissions } from "~/services/auth";
@@ -35,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
if (createSupplierContact.error) {
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/contacts`,
await flash(
request,
error(createSupplierContact.error, "Failed to create supplier contact")
@@ -44,7 +45,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/contacts`,
await flash(request, success("Supplier contact created"))
);
}
+
+export default function SupplierContactsNewRoute() {
+ const initialValues = {
+ firstName: "",
+ lastName: "",
+ email: "",
+ };
+
+ return <SupplierContactForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.tsx
new file mode 100644
index 0000000000..ae0d5f8769
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.contacts.tsx
@@ -0,0 +1,37 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { getSupplierContacts, SupplierContacts } from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw new Error("Could not find supplierId");
+
+ const contacts = await getSupplierContacts(client, supplierId);
+ if (contacts.error) {
+ return redirect(
+ `/x/supplier/${supplierId}`,
+ await flash(
+ request,
+ error(contacts.error, "Failed to fetch supplier contacts")
+ )
+ );
+ }
+
+ return json({
+ contacts: contacts.data ?? [],
+ });
+}
+
+export default function SupplierContactsRoute() {
+ const { contacts } = useLoaderData<typeof loader>();
+
+ return <SupplierContacts contacts={contacts} />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.index.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.index.tsx
new file mode 100644
index 0000000000..21d5c30063
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.index.tsx
@@ -0,0 +1,79 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useParams } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import { useRouteData } from "~/hooks";
+import type { SupplierDetail } from "~/modules/purchasing";
+import {
+ SupplierForm,
+ supplierValidator,
+ updateSupplier,
+} from "~/modules/purchasing";
+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 }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const validation = await supplierValidator.validate(await request.formData());
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ if (!id) {
+ return redirect(
+ "/x/purchasing/suppliers",
+ await flash(request, error(null, "Failed to update supplier"))
+ );
+ }
+
+ const update = await updateSupplier(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ });
+ if (update.error) {
+ return redirect(
+ "/x/purchasing/suppliers",
+ await flash(request, error(update.error, "Failed to update supplier"))
+ );
+ }
+
+ return json(null, await flash(request, success("Updated supplier")));
+}
+
+export default function SupplierEditRoute() {
+ const { supplierId } = useParams();
+ if (!supplierId) throw new Error("Could not find supplierId");
+ const routeData = useRouteData<{ supplier: SupplierDetail }>(
+ `/x/supplier/${supplierId}`
+ );
+
+ if (!routeData?.supplier) return null;
+
+ const initialValues = {
+ id: routeData?.supplier?.id ?? undefined,
+ name: routeData?.supplier?.name ?? "",
+ supplierTypeId: routeData?.supplier?.supplierTypeId ?? undefined,
+ supplierStatusId: routeData?.supplier?.supplierStatusId ?? undefined,
+ accountManagerId: routeData?.supplier?.accountManagerId ?? undefined,
+ taxId: routeData?.supplier?.taxId ?? "",
+ defaultCurrencyCode: routeData?.supplier?.defaultCurrencyCode ?? "",
+ defaultPaymentTermId:
+ routeData?.supplier?.defaultPaymentTermId ?? undefined,
+ defaultShippingMethodId:
+ routeData?.supplier?.defaultShippingMethodId ?? undefined,
+ defaultShippingTermId:
+ routeData?.supplier?.defaultShippingTermId ?? undefined,
+ };
+
+ return <SupplierForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.$supplierLocationId.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.$supplierLocationId.tsx
new file mode 100644
index 0000000000..021c03d8c6
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.$supplierLocationId.tsx
@@ -0,0 +1,99 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import {
+ getSupplierLocation,
+ SupplierLocationForm,
+ supplierLocationValidator,
+ updateSupplierLocation,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, badRequest, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { supplierId, supplierLocationId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+ if (!supplierLocationId) throw notFound("supplierLocationId not found");
+
+ const location = await getSupplierLocation(client, supplierLocationId);
+ if (location.error) {
+ return redirect(
+ `/x/supplier/${supplierId}/locations`,
+ await flash(
+ request,
+ error(location.error, "Failed to get supplier location")
+ )
+ );
+ }
+
+ return json({
+ location: location.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ update: "purchasing",
+ });
+
+ const { supplierId, supplierLocationId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+ if (!supplierLocationId) throw notFound("supplierLocationId not found");
+
+ const validation = await supplierLocationValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, addressId, ...address } = validation.data;
+
+ if (addressId === undefined)
+ throw badRequest("addressId is undefined in form data");
+
+ const update = await updateSupplierLocation(client, {
+ addressId,
+ address,
+ });
+ if (update.error) {
+ return redirect(
+ `/x/supplier/${supplierId}/locations`,
+ await flash(
+ request,
+ error(update.error, "Failed to update supplier address")
+ )
+ );
+ }
+
+ return redirect(
+ `/x/supplier/${supplierId}/locations`,
+ await flash(request, success("Supplier address updated"))
+ );
+}
+
+export default function EditSupplierLocationRoute() {
+ const { location } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: location?.id ?? undefined,
+ addressId: location?.address?.id ?? undefined,
+
+ addressLine1: location?.address?.addressLine1 ?? "",
+ addressLine2: location?.address?.addressLine2 ?? "",
+ city: location?.address?.city ?? "",
+ state: location?.address?.state ?? "",
+ postalCode: location?.address?.postalCode ?? "",
+ };
+
+ return <SupplierLocationForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.delete.$supplierLocationId.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx
similarity index 92%
rename from apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.delete.$supplierLocationId.tsx
rename to apps/carbon/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx
index 1148e86b51..0c44239916 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.delete.$supplierLocationId.tsx
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx
@@ -28,7 +28,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
if (deleteSupplierLocationError) {
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/locations`,
await flash(
request,
error(deleteSupplierLocationError, "Failed to delete supplier location")
@@ -37,7 +37,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/locations`,
await flash(request, success("Successfully deleted supplier location"))
);
}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.new.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.new.tsx
similarity index 84%
rename from apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.new.tsx
rename to apps/carbon/app/routes/x+/supplier+/$supplierId.locations.new.tsx
index a43ce2ee1e..7daf7d46dc 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.$supplierId.location.new.tsx
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.new.tsx
@@ -3,6 +3,7 @@ import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
import {
insertSupplierLocation,
+ SupplierLocationForm,
supplierLocationValidator,
} from "~/modules/purchasing";
import { requirePermissions } from "~/services/auth";
@@ -35,7 +36,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
});
if (createSupplierLocation.error) {
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/locations`,
await flash(
request,
error(
@@ -47,7 +48,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}/locations`,
await flash(request, success("Supplier location created"))
);
}
+
+export default function SupplierLocationsNewRoute() {
+ const initialValues = {};
+
+ return <SupplierLocationForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.tsx
new file mode 100644
index 0000000000..a3f6d246e6
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.locations.tsx
@@ -0,0 +1,37 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { getSupplierLocations, SupplierLocations } from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw new Error("Could not find supplierId");
+
+ const locations = await getSupplierLocations(client, supplierId);
+ if (locations.error) {
+ return redirect(
+ `/x/supplier/${supplierId}`,
+ await flash(
+ request,
+ error(locations.error, "Failed to fetch supplier locations")
+ )
+ );
+ }
+
+ return json({
+ locations: locations.data ?? [],
+ });
+}
+
+export default function SupplierLocationsRoute() {
+ const { locations } = useLoaderData<typeof loader>();
+
+ return <SupplierLocations locations={locations} />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.tsx
new file mode 100644
index 0000000000..63f2208218
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.tsx
@@ -0,0 +1,61 @@
+import { Grid } from "@chakra-ui/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import {
+ getSupplier,
+ getSupplierContacts,
+ getSupplierLocations,
+ SupplierHeader,
+ SupplierSidebar,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw new Error("Could not find supplierId");
+
+ const [supplier, contacts, locations] = await Promise.all([
+ getSupplier(client, supplierId),
+ getSupplierContacts(client, supplierId),
+ getSupplierLocations(client, supplierId),
+ ]);
+
+ if (supplier.error) {
+ return redirect(
+ "/x/purchasing/suppliers",
+ await flash(
+ request,
+ error(supplier.error, "Failed to load supplier summary")
+ )
+ );
+ }
+
+ return json({
+ supplier: supplier.data,
+ contacts: contacts.data ?? [],
+ locations: locations.data ?? [],
+ });
+}
+
+export default function SupplierRoute() {
+ return (
+ <>
+ <SupplierHeader />
+ <Grid
+ gridTemplateColumns={["1fr", "1fr", "1fr 4fr"]}
+ gridColumnGap={4}
+ w="full"
+ >
+ <SupplierSidebar />
+ <Outlet />
+ </Grid>
+ </>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/_layout.tsx b/apps/carbon/app/routes/x+/supplier+/_layout.tsx
new file mode 100644
index 0000000000..e934bb672b
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/_layout.tsx
@@ -0,0 +1,50 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderFunctionArgs, MetaFunction } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { getPaymentTermsList } from "~/modules/accounting";
+import {
+ getShippingMethodsList,
+ getShippingTermsList,
+} from "~/modules/inventory";
+import { getSupplierStatuses, getSupplierTypes } from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+
+export const meta: MetaFunction = () => {
+ return [{ title: "Carbon | Part" }];
+};
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const [
+ supplierTypes,
+ supplierStatuses,
+ paymentTerms,
+ shippingMethods,
+ shippingTerms,
+ ] = await Promise.all([
+ getSupplierTypes(client),
+ getSupplierStatuses(client),
+ getPaymentTermsList(client),
+ getShippingMethodsList(client),
+ getShippingTermsList(client),
+ ]);
+
+ return json({
+ supplierStatuses: supplierStatuses.data ?? [],
+ supplierTypes: supplierTypes.data ?? [],
+ paymentTerms: paymentTerms.data ?? [],
+ shippingMethods: shippingMethods.data ?? [],
+ shippingTerms: shippingTerms.data ?? [],
+ });
+}
+
+export default function SupplierRoute() {
+ return (
+ <VStack w="full" h="full" spacing={4} p={4}>
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx b/apps/carbon/app/routes/x+/supplier+/new.tsx
similarity index 96%
rename from apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
rename to apps/carbon/app/routes/x+/supplier+/new.tsx
index afcfec8954..fbbd97616c 100644
--- a/apps/carbon/app/routes/x+/purchasing+/suppliers.new.tsx
+++ b/apps/carbon/app/routes/x+/supplier+/new.tsx
@@ -42,7 +42,7 @@ export async function action({ request }: ActionFunctionArgs) {
const supplierId = createSupplier.data?.id;
return redirect(
- `/x/purchasing/suppliers/${supplierId}`,
+ `/x/supplier/${supplierId}`,
await flash(request, success("Created supplier"))
);
}
diff --git a/apps/carbon/app/routes/x+/users+/customers.new.tsx b/apps/carbon/app/routes/x+/users+/customers.new.tsx
index 94937909fd..d460966922 100644
--- a/apps/carbon/app/routes/x+/users+/customers.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/customers.new.tsx
@@ -13,8 +13,7 @@ import { assertIsPost } from "~/utils/http";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client } = await requirePermissions(request, {
- view: "sales",
- update: "users",
+ view: "users",
});
const validation = await createCustomerAccountValidator.validate(
@@ -25,12 +24,23 @@ export async function action({ request }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const customerRedirect = searchParams.get("customer");
+
const { id, customer } = validation.data;
const result = await createCustomerAccount(client, {
id,
customerId: customer,
});
+ if (customerRedirect) {
+ return redirect(
+ `/x/customer/${customerRedirect}/contacts`,
+ await flash(request, result)
+ );
+ }
+
return redirect("/x/users/customers", await flash(request, result));
}
diff --git a/apps/carbon/app/routes/x+/users+/suppliers.new.tsx b/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
index c1f1c1ec5e..de56dd2947 100644
--- a/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
+++ b/apps/carbon/app/routes/x+/users+/suppliers.new.tsx
@@ -36,7 +36,7 @@ export async function action({ request }: ActionFunctionArgs) {
if (supplierRedirect) {
return redirect(
- `/x/purchasing/suppliers/${supplierRedirect}`,
+ `/x/supplier/${supplierRedirect}/contacts`,
await flash(request, result)
);
}
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index ccba1ae945..1f0a0aa407 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -7,7 +7,7 @@
"build": "remix build",
"dev": "run-p dev:*",
"dev:remix": "remix dev",
- "start": "remix-serve build",
+ "start": "remix-serve ./build/index.js",
"clean": "rimraf .cache .turbo node_modules dist build",
"lint": "TIMING=1 eslint \"app/**/*.ts*\"",
"types": "tsc"
@@ -30,7 +30,8 @@
"@remix-run/node": "~2.0.0",
"@remix-run/react": "~2.0.0",
"@remix-run/serve": "~2.0.0",
- "@vercel/remix": "1.19.3",
+ "@vercel/analytics": "^1.0.2",
+ "@vercel/remix": "2.0.0",
"@remix-validated-form/with-zod": "^2.0.6",
"@supabase/supabase-js": "^2.33.1",
"@tanstack/react-table": "^8.9.3",
diff --git a/apps/carbon/remix.config.js b/apps/carbon/remix.config.js
index 3873a19803..41f85dcc1f 100644
--- a/apps/carbon/remix.config.js
+++ b/apps/carbon/remix.config.js
@@ -4,12 +4,15 @@ const { flatRoutes } = require("remix-flat-routes");
/** @type {import('@remix-run/dev').AppConfig} */
module.exports = {
+ // appDirectory: "app",
+ // assetsBuildDirectory: "public/build",
+ // publicPath: "/build/",
+ // serverBuildPath: "build/index.js",
future: {},
ignoredRouteFiles: ["**/.*"],
serverModuleFormat: "cjs",
serverPlatform: "node",
serverMinify: false,
-
routes: async (defineRoutes) => {
return flatRoutes("routes", defineRoutes, {
// eslint-disable-next-line no-undef
diff --git a/apps/carbon/server.js b/apps/carbon/server.js
deleted file mode 100644
index 4e2a0e00e7..0000000000
--- a/apps/carbon/server.js
+++ /dev/null
@@ -1,4 +0,0 @@
-import { createRequestHandler } from "@remix-run/vercel";
-import * as build from "@remix-run/dev/server-build";
-
-export default createRequestHandler({ build, mode: process.env.NODE_ENV });
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index b2a0e79807..6bcb21b193 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1352,6 +1352,10 @@ export interface Database {
createdBy: string | null;
customerStatusId: string | null;
customerTypeId: string | null;
+ defaultCurrencyCode: string | null;
+ defaultPaymentTermId: string | null;
+ defaultShippingMethodId: string | null;
+ defaultShippingTermId: string | null;
id: string;
logo: string | null;
name: string;
@@ -1365,6 +1369,10 @@ export interface Database {
createdBy?: string | null;
customerStatusId?: string | null;
customerTypeId?: string | null;
+ defaultCurrencyCode?: string | null;
+ defaultPaymentTermId?: string | null;
+ defaultShippingMethodId?: string | null;
+ defaultShippingTermId?: string | null;
id?: string;
logo?: string | null;
name: string;
@@ -1378,6 +1386,10 @@ export interface Database {
createdBy?: string | null;
customerStatusId?: string | null;
customerTypeId?: string | null;
+ defaultCurrencyCode?: string | null;
+ defaultPaymentTermId?: string | null;
+ defaultShippingMethodId?: string | null;
+ defaultShippingTermId?: string | null;
id?: string;
logo?: string | null;
name?: string;
@@ -1422,6 +1434,24 @@ export interface Database {
referencedRelation: "customerType";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "customer_defaultPaymentTermId_fkey";
+ columns: ["defaultPaymentTermId"];
+ referencedRelation: "paymentTerm";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "customer_defaultShippingMethodId_fkey";
+ columns: ["defaultShippingMethodId"];
+ referencedRelation: "shippingMethod";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "customer_defaultShippingTermId_fkey";
+ columns: ["defaultShippingTermId"];
+ referencedRelation: "shippingTerm";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "customer_updatedBy_fkey";
columns: ["updatedBy"];
@@ -1456,6 +1486,12 @@ export interface Database {
referencedRelation: "customer";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "customerAccount_customerId_fkey";
+ columns: ["customerId"];
+ referencedRelation: "customers_view";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "customerAccount_id_fkey";
columns: ["id"];
@@ -1505,6 +1541,12 @@ export interface Database {
referencedRelation: "customer";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "customerContact_customerId_fkey";
+ columns: ["customerId"];
+ referencedRelation: "customers_view";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "customerContact_customerLocationId_fkey";
columns: ["customerLocationId"];
@@ -1553,6 +1595,12 @@ export interface Database {
columns: ["customerId"];
referencedRelation: "customer";
referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "customerLocation_customerId_fkey";
+ columns: ["customerId"];
+ referencedRelation: "customers_view";
+ referencedColumns: ["id"];
}
];
};
@@ -4469,6 +4517,12 @@ export interface Database {
referencedRelation: "customer";
referencedColumns: ["id"];
},
+ {
+ foreignKeyName: "purchaseOrderDelivery_customerId_fkey";
+ columns: ["customerId"];
+ referencedRelation: "customers_view";
+ referencedColumns: ["id"];
+ },
{
foreignKeyName: "purchaseOrderDelivery_customerLocationId_fkey";
columns: ["customerLocationId"];
@@ -6828,6 +6882,30 @@ export interface Database {
}
];
};
+ customers_view: {
+ Row: {
+ customerStatusId: string | null;
+ customerTypeId: string | null;
+ id: string | null;
+ name: string | null;
+ status: string | null;
+ type: string | null;
+ };
+ Relationships: [
+ {
+ foreignKeyName: "customer_customerStatusId_fkey";
+ columns: ["customerStatusId"];
+ referencedRelation: "customerStatus";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "customer_customerTypeId_fkey";
+ columns: ["customerTypeId"];
+ referencedRelation: "customerType";
+ referencedColumns: ["id"];
+ }
+ ];
+ };
documents_labels_view: {
Row: {
label: string | null;
diff --git a/packages/database/supabase/migrations/20230123212853_search.sql b/packages/database/supabase/migrations/20230123212853_search.sql
index d74fc40126..5a2a51df2e 100644
--- a/packages/database/supabase/migrations/20230123212853_search.sql
+++ b/packages/database/supabase/migrations/20230123212853_search.sql
@@ -58,7 +58,7 @@ CREATE FUNCTION public.create_customer_search_result()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.search(name, entity, uuid, link)
- VALUES (new.name, 'Customer', new.id, '/x/sales/customers/' || new.id);
+ VALUES (new.name, 'Customer', new.id, '/x/customer/' || new.id);
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
@@ -86,7 +86,7 @@ CREATE FUNCTION public.create_supplier_search_result()
RETURNS TRIGGER AS $$
BEGIN
INSERT INTO public.search(name, entity, uuid, link)
- VALUES (new.name, 'Supplier', new.id, '/x/purchasing/suppliers/' || new.id);
+ VALUES (new.name, 'Supplier', new.id, '/x/supplier/' || new.id);
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20230330024716_parts.sql b/packages/database/supabase/migrations/20230330024716_parts.sql
index 42e6c35f8b..073cbeea7f 100644
--- a/packages/database/supabase/migrations/20230330024716_parts.sql
+++ b/packages/database/supabase/migrations/20230330024716_parts.sql
@@ -238,7 +238,7 @@ END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER update_part_search_result
- AFTER UPDATE on public.customer
+ AFTER UPDATE on public.part
FOR EACH ROW EXECUTE PROCEDURE public.update_part_search_result();
diff --git a/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
index 66bbf8e4c7..039a928ac3 100644
--- a/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
+++ b/packages/database/supabase/migrations/20230702114301_purchasing-rls.sql
@@ -64,7 +64,7 @@ END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
CREATE TRIGGER update_purchase_order_search_result
- AFTER UPDATE on public.customer
+ AFTER UPDATE on public."purchaseOrder"
FOR EACH ROW EXECUTE PROCEDURE public.update_purchase_order_search_result();
diff --git a/packages/database/supabase/migrations/20230704160029_supplier-view.sql b/packages/database/supabase/migrations/20230704160029_supplier-view.sql
index 5fe4c4ee35..aa2fd19121 100644
--- a/packages/database/supabase/migrations/20230704160029_supplier-view.sql
+++ b/packages/database/supabase/migrations/20230704160029_supplier-view.sql
@@ -24,4 +24,25 @@ CREATE VIEW "suppliers_view" AS
COUNT(*) AS "count"
FROM "partSupplier"
GROUP BY "supplierId"
- ) p ON p."supplierId" = s.id;
\ No newline at end of file
+ ) p ON p."supplierId" = s.id;
+
+ CREATE VIEW "customers_view" AS
+ SELECT
+ c.id,
+ c.name,
+ c."customerTypeId",
+ ct.name AS "type",
+ c."customerStatusId",
+ cs.name AS "status"
+ -- so.count AS "orderCount"
+ FROM "customer" c
+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId";
+
+ -- LEFT JOIN (
+ -- SELECT
+ -- "customerId",
+ -- COUNT(*) AS "count"
+ -- FROM "salesOrder"
+ -- GROUP BY "customerId"
+ -- ) so ON so."customerId" = c.id
diff --git a/packages/database/supabase/migrations/20230923083559_customer-details.sql b/packages/database/supabase/migrations/20230923083559_customer-details.sql
new file mode 100644
index 0000000000..c07073edbc
--- /dev/null
+++ b/packages/database/supabase/migrations/20230923083559_customer-details.sql
@@ -0,0 +1,10 @@
+ALTER TABLE "customer"
+ ADD COLUMN "defaultCurrencyCode" TEXT,
+ ADD COLUMN "defaultPaymentTermId" TEXT,
+ ADD COLUMN "defaultShippingMethodId" TEXT,
+ ADD COLUMN "defaultShippingTermId" TEXT;
+
+ALTER TABLE "customer"
+ ADD CONSTRAINT "customer_defaultPaymentTermId_fkey" FOREIGN KEY ("defaultPaymentTermId") REFERENCES "paymentTerm" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "customer_defaultShippingMethodId_fkey" FOREIGN KEY ("defaultShippingMethodId") REFERENCES "shippingMethod" ("id") ON DELETE SET NULL,
+ ADD CONSTRAINT "customer_defaultShippingTermId_fkey" FOREIGN KEY ("defaultShippingTermId") REFERENCES "shippingTerm" ("id") ON DELETE SET NULL;
diff --git a/packages/react/src/Count/Count.tsx b/packages/react/src/Count/Count.tsx
index 07e7e270da..3e25b20e6d 100644
--- a/packages/react/src/Count/Count.tsx
+++ b/packages/react/src/Count/Count.tsx
@@ -1,5 +1,5 @@
-import { Flex } from "@chakra-ui/react";
import type { BoxProps } from "@chakra-ui/react";
+import { Flex } from "@chakra-ui/react";
export interface CountProps extends BoxProps {
count: number;
@@ -12,7 +12,7 @@ const Count = ({ count, ...props }: CountProps) => {
as="span"
bg="gray.700"
borderRadius="full"
- fontSize="sm"
+ fontSize={12}
h={5}
minW={5}
alignItems="center"
diff --git a/www/pages/docs/tech-stack.mdx b/www/pages/docs/tech-stack.mdx
index dbb310ef6c..b33b9fbcb2 100644
--- a/www/pages/docs/tech-stack.mdx
+++ b/www/pages/docs/tech-stack.mdx
@@ -31,7 +31,9 @@ We have a package called [@carbon/react](https://github.com/barbinbrad/carbon/tr
## Chakra UI
-[Chakra UI](https://chakra-ui.com) is a lightweight and flexible component library that gives us accessibility, full-control, and simplicty. It implements the WAI-ARIA spec behaviors with some basic primitive components (like Button and Modal) while providing an easy-to-modify API for customizing the design.
+[Chakra UI](https://chakra-ui.com) is a flexible component library that gives us accessibility, full-control, and simplicty. It implements the WAI-ARIA spec behaviors with some basic primitive components (like Button and Modal) while providing an easy-to-modify API for customizing the design.
+
+While it's not the most performant choice, it provides an easy-to-use developer experience that should allow contributors to quickly build out new features without an expertise in CSS.
Here's an example of a Chakra UI button:
diff --git a/yarn.lock b/yarn.lock
index 7e174e91cd..200aeb1abe 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2962,21 +2962,6 @@
dependencies:
"@remix-run/node" "2.0.0"
-"@remix-run/[email protected]":
- version "1.19.3"
- resolved "https://registry.yarnpkg.com/@remix-run/node/-/node-1.19.3.tgz#d27e2f742fc45379525cb3fca466a883ca06d6c9"
- integrity sha512-z5qrVL65xLXIUpU4mkR4MKlMeKARLepgHAk4W5YY3IBXOreRqOGUC70POViYmY7x38c2Ia1NwqL80H+0h7jbMw==
- dependencies:
- "@remix-run/server-runtime" "1.19.3"
- "@remix-run/web-fetch" "^4.3.6"
- "@remix-run/web-file" "^3.0.3"
- "@remix-run/web-stream" "^1.0.4"
- "@web3-storage/multipart-parser" "^1.0.0"
- abort-controller "^3.0.0"
- cookie-signature "^1.1.0"
- source-map-support "^0.5.21"
- stream-slice "^0.1.2"
-
"@remix-run/[email protected]", "@remix-run/node@~2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@remix-run/node/-/node-2.0.0.tgz#9ed9215cb59dae005229609b911274602df7b851"
@@ -3000,11 +2985,6 @@
"@remix-run/server-runtime" "2.0.0"
react-router-dom "6.16.0"
-"@remix-run/[email protected]":
- version "1.7.2"
- resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.7.2.tgz#cba1cf0a04bc04cb66027c51fa600e9cbc388bc8"
- integrity sha512-7Lcn7IqGMV+vizMPoEl5F0XDshcdDYtMI6uJLQdQz5CfZAwy3vvGKYSUk789qndt5dEC4HfSjviSYlSoHGL2+A==
-
"@remix-run/[email protected]":
version "1.9.0"
resolved "https://registry.yarnpkg.com/@remix-run/router/-/router-1.9.0.tgz#9033238b41c4cbe1e961eccb3f79e2c588328cf6"
@@ -3024,18 +3004,6 @@
morgan "^1.10.0"
source-map-support "^0.5.21"
-"@remix-run/[email protected]":
- version "1.19.3"
- resolved "https://registry.yarnpkg.com/@remix-run/server-runtime/-/server-runtime-1.19.3.tgz#206b55337c266c5bc254878f8ff3cd5677cc60fb"
- integrity sha512-KzQ+htUsKqpBgKE2tWo7kIIGy3MyHP58Io/itUPvV+weDjApwr9tQr9PZDPA3yAY6rAzLax7BU0NMSYCXWFY5A==
- dependencies:
- "@remix-run/router" "1.7.2"
- "@types/cookie" "^0.4.1"
- "@web3-storage/multipart-parser" "^1.0.0"
- cookie "^0.4.1"
- set-cookie-parser "^2.4.8"
- source-map "^0.7.3"
-
"@remix-run/[email protected]":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@remix-run/server-runtime/-/server-runtime-2.0.0.tgz#d7d89e1d8b17ce599cabb14d1d0a87b4b833a2d6"
@@ -3064,7 +3032,7 @@
"@remix-run/web-stream" "^1.1.0"
web-encoding "1.1.5"
-"@remix-run/web-fetch@^4.3.6", "@remix-run/web-fetch@^4.4.0":
+"@remix-run/web-fetch@^4.4.0":
version "4.4.0"
resolved "https://registry.yarnpkg.com/@remix-run/web-fetch/-/web-fetch-4.4.0.tgz#23919c0f5a6649d133c42e72f2ca08dad18693c1"
integrity sha512-j6vswnGteHd3N5Y2lb5sRKP+NxChVCd1goXRDAanTMFfgxsCV/1ItlJFY8G/F4AESkDydcZ6tz6gAsttkGDiMA==
@@ -3077,7 +3045,7 @@
data-uri-to-buffer "^3.0.1"
mrmime "^1.0.0"
-"@remix-run/web-file@^3.0.3", "@remix-run/web-file@^3.1.0":
+"@remix-run/web-file@^3.1.0":
version "3.1.0"
resolved "https://registry.yarnpkg.com/@remix-run/web-file/-/web-file-3.1.0.tgz#07219021a2910e90231bc30ca1ce693d0e9d3825"
integrity sha512-dW2MNGwoiEYhlspOAXFBasmLeYshyAyhIdrlXBi06Duex5tDr3ut2LFKVj7tyHLmn8nnNwFf1BjNbkQpygC2aQ==
@@ -3091,7 +3059,7 @@
dependencies:
web-encoding "1.1.5"
-"@remix-run/web-stream@^1.0.4", "@remix-run/web-stream@^1.1.0":
+"@remix-run/web-stream@^1.1.0":
version "1.1.0"
resolved "https://registry.yarnpkg.com/@remix-run/web-stream/-/web-stream-1.1.0.tgz#b93a8f806c2c22204930837c44d81fdedfde079f"
integrity sha512-KRJtwrjRV5Bb+pM7zxcTJkhIqWWSy+MYsIxHK+0m5atcznsf15YwUBWHWulZerV2+vvHH1Lp1DD7pw6qKW8SgA==
@@ -4118,13 +4086,18 @@
resolved "https://registry.yarnpkg.com/@vanilla-extract/private/-/private-1.0.3.tgz#7ec72bc2ff6fe51f9d650f962e8d1989b073690f"
integrity sha512-17kVyLq3ePTKOkveHxXuIJZtGYs+cSoev7BlP+Lf4916qfDhk/HBjvlYDe8egrea7LNPHKwSZJK/bzZC+Q6AwQ==
-"@vercel/[email protected]":
- version "1.19.3"
- resolved "https://registry.yarnpkg.com/@vercel/remix/-/remix-1.19.3.tgz#ff6fa0dcf22c2d143a9214140d78699a5b7aca41"
- integrity sha512-YLgtsuTkTrmLL1t5QFr2LV0U2nqL7gJmEegTgmACcB32Gnps4bnFjv4EAgt7eUurcEzcaGSfDSONdMiEUjZXTQ==
+"@vercel/analytics@^1.0.2":
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/@vercel/analytics/-/analytics-1.0.2.tgz#7af719a1bf33734840aee6f04eb548d2cedab9ec"
+ integrity sha512-BZFxVrv24VbNNl5xMxqUojQIegEeXMI6rX3rg1uVLYUEXsuKNBSAEQf4BWEcjQDp/8aYJOj6m8V4PUA3x/cxgg==
+
+"@vercel/[email protected]":
+ version "2.0.0"
+ resolved "https://registry.yarnpkg.com/@vercel/remix/-/remix-2.0.0.tgz#e7fbfc8a17059208092b06b6019e50c8a918d7d2"
+ integrity sha512-nwv1Z0ucVAARp399JOq/+Vf174E457P8BIJuDn63NAudgcKUWPVmqbfg1EP0jIa+FsjNQX1YXyExZ47k3sAfHg==
dependencies:
- "@remix-run/node" "1.19.3"
- "@remix-run/server-runtime" "1.19.3"
+ "@remix-run/node" "2.0.0"
+ "@remix-run/server-runtime" "2.0.0"
isbot "^3.6.8"