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.

Contractors (#26)

Brad Barbind175c31e90bf
diff --git a/SCHEMA.md b/SCHEMA.md
index 95d642f798..3623a48a0b 100644
--- a/SCHEMA.md
+++ b/SCHEMA.md
@@ -2496,9 +2496,101 @@ CREATE TABLE "partner" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "partner_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "partner_id_fkey" FOREIGN KEY ("id") REFERENCES "supplier"("id"),
+ CONSTRAINT "partner_id_fkey" FOREIGN KEY ("id") REFERENCES "supplierLocation"("id"),
CONSTRAINT "partner_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partner_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
+
+CREATE TABLE "partnerAbility" (
+ "partnerId" TEXT NOT NULL,
+ "abilityId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "partnerAbility_pkey" PRIMARY KEY ("partnerId", "abilityId"),
+ CONSTRAINT "partnerAbility_partnerId_fkey" FOREIGN KEY ("partnerId") REFERENCES "partner"("id") ON DELETE CASCADE,
+ CONSTRAINT "partnerAbility_abilityId_fkey" FOREIGN KEY ("abilityId") REFERENCES "ability"("id") ON DELETE CASCADE,
+ CONSTRAINT "partnerAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
+);
+
+CREATE VIEW "partners_query" AS
+ SELECT
+ p.id AS "supplierLocationId",
+ p."active",
+ p."hoursPerWeek",
+ s.id AS "supplierId",
+ s.name AS "supplierName",
+ a.city,
+ a.state,
+ array_agg(pa."abilityId") AS "abilityIds"
+ FROM "partner" p
+ INNER JOIN "supplierLocation" sl
+ ON sl.id = p.id
+ INNER JOIN "supplier" s
+ ON s.id = sl."supplierId"
+ INNER JOIN "address" a
+ ON a.id = sl."addressId"
+ INNER JOIN "partnerAbility" pa
+ ON pa."partnerId" = p.id
+ WHERE p."active" = true
+ GROUP BY p.id, p.active, p."hoursPerWeek", s.id, a.id, s.name, a.city, a.state
+;
+```
+
+
+
+## `contractors`
+
+```sql
+CREATE TABLE "contractor" (
+ "id" TEXT NOT NULL,
+ "hoursPerWeek" INTEGER NOT NULL DEFAULT 0,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "contractor_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "contractor_id_fkey" FOREIGN KEY ("id") REFERENCES "supplierContact"("id"),
+ CONSTRAINT "contractor_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "contractor_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE TABLE "contractorAbility" (
+ "contractorId" TEXT NOT NULL,
+ "abilityId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "contractorAbility_pkey" PRIMARY KEY ("contractorId", "abilityId"),
+ CONSTRAINT "contractorAbility_contractorId_fkey" FOREIGN KEY ("contractorId") REFERENCES "contractor"("id") ON DELETE CASCADE,
+ CONSTRAINT "contractorAbility_abilityId_fkey" FOREIGN KEY ("abilityId") REFERENCES "ability"("id") ON DELETE CASCADE,
+ CONSTRAINT "contractorAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
+);
+
+CREATE VIEW "contractors_query" AS
+ SELECT
+ p.id AS "supplierContactId",
+ p."active",
+ p."hoursPerWeek",
+ s.id AS "supplierId",
+ s.name AS "supplierName",
+ c."firstName",
+ c."lastName",
+ c."email",
+ array_agg(pa."abilityId") AS "abilityIds"
+ FROM "contractor" p
+ INNER JOIN "supplierContact" sc
+ ON sc.id = p.id
+ INNER JOIN "supplier" s
+ ON s.id = sc."supplierId"
+ INNER JOIN "contact" c
+ ON c.id = sc."contactId"
+ INNER JOIN "contractorAbility" pa
+ ON pa."contractorId" = p.id
+ WHERE p."active" = true
+ GROUP BY p.id, p.active, p."hoursPerWeek", s.id, c.id, s.name, c."firstName", c."lastName", c."email"
+;
```
diff --git a/apps/carbon/app/components/Address/Address.tsx b/apps/carbon/app/components/Address/Address.tsx
index 8d2bc7cbd4..b11ad09316 100644
--- a/apps/carbon/app/components/Address/Address.tsx
+++ b/apps/carbon/app/components/Address/Address.tsx
@@ -1,7 +1,7 @@
import { ActionMenu } from "@carbon/react";
import { Grid, Icon, MenuItem, Text, VStack } from "@chakra-ui/react";
-import { BsPencilSquare, BsPinMapFill } from "react-icons/bs";
-import { IoMdTrash } from "react-icons/io";
+import { BsPinMapFill } from "react-icons/bs";
+import type { Action } from "~/types";
type AddressProps = {
address: {
@@ -10,11 +10,10 @@ type AddressProps = {
addressLine1: string | null;
postalCode: string | null;
};
- onEdit?: () => void;
- onDelete?: () => void;
+ actions: Action[];
};
-const Address = ({ address, onEdit, onDelete }: AddressProps) => {
+const Address = ({ address, actions }: AddressProps) => {
const location = `${address.city ?? ""}, ${address.state ?? ""}`;
const addressZip = `${address.addressLine1 ?? ""} ${
address.postalCode ?? ""
@@ -30,18 +29,17 @@ const Address = ({ address, onEdit, onDelete }: AddressProps) => {
{addressZip}
</Text>
</VStack>
- {(onEdit || onDelete) && (
+ {actions.length > 0 && (
<ActionMenu>
- {onEdit && (
- <MenuItem icon={<BsPencilSquare />} onClick={onEdit}>
- Edit Location
+ {actions.map((action) => (
+ <MenuItem
+ key={action.label}
+ icon={action.icon}
+ onClick={action.onClick}
+ >
+ {action.label}
</MenuItem>
- )}
- {onDelete && (
- <MenuItem icon={<IoMdTrash />} onClick={onDelete}>
- Delete Location
- </MenuItem>
- )}
+ ))}
</ActionMenu>
)}
</Grid>
diff --git a/apps/carbon/app/components/Contact/Contact.tsx b/apps/carbon/app/components/Contact/Contact.tsx
index 78717d9a86..f067d4e870 100644
--- a/apps/carbon/app/components/Contact/Contact.tsx
+++ b/apps/carbon/app/components/Contact/Contact.tsx
@@ -1,7 +1,6 @@
import { ActionMenu, Dot } from "@carbon/react";
import { Avatar, Grid, MenuItem, Text, VStack } from "@chakra-ui/react";
-import { BsPencilSquare, BsShieldLock } from "react-icons/bs";
-import { IoMdTrash } from "react-icons/io";
+import type { Action } from "~/types";
type ContactProps = {
contact: {
@@ -13,9 +12,7 @@ type ContactProps = {
id: string;
active: boolean | null;
} | null;
- onCreateAccount?: () => void;
- onEdit?: () => void;
- onDelete?: () => void;
+ actions: Action[];
};
enum UserStatus {
@@ -24,13 +21,7 @@ enum UserStatus {
None,
}
-const Contact = ({
- contact,
- user,
- onEdit,
- onDelete,
- onCreateAccount,
-}: ContactProps) => {
+const Contact = ({ contact, user, actions }: ContactProps) => {
const name = `${contact.firstName ?? ""} ${contact.lastName ?? ""}`;
const userStatus = user
? user.active
@@ -55,23 +46,17 @@ const Contact = ({
{contact.email ?? ""}
</Text>
</VStack>
- {(onEdit || onDelete || onCreateAccount) && (
+ {actions.length > 0 && (
<ActionMenu>
- {onEdit && (
- <MenuItem icon={<BsPencilSquare />} onClick={onEdit}>
- Edit Contact
+ {actions.map((action) => (
+ <MenuItem
+ key={action.label}
+ icon={action.icon}
+ onClick={action.onClick}
+ >
+ {action.label}
</MenuItem>
- )}
- {onDelete && (
- <MenuItem icon={<IoMdTrash />} onClick={onDelete}>
- Delete Contact
- </MenuItem>
- )}
- {onCreateAccount && (
- <MenuItem icon={<BsShieldLock />} onClick={onCreateAccount}>
- Create Account
- </MenuItem>
- )}
+ ))}
</ActionMenu>
)}
</Grid>
diff --git a/apps/carbon/app/components/Form/Abilities.tsx b/apps/carbon/app/components/Form/Abilities.tsx
new file mode 100644
index 0000000000..a93bee2afc
--- /dev/null
+++ b/apps/carbon/app/components/Form/Abilities.tsx
@@ -0,0 +1,120 @@
+import { Select } from "@carbon/react";
+import {
+ Box,
+ FormControl,
+ FormErrorMessage,
+ FormHelperText,
+ FormLabel,
+} from "@chakra-ui/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useMemo } from "react";
+import { useControlField, useField } from "remix-validated-form";
+import type { getAbilitiesList } from "~/modules/resources";
+import type { SelectProps } from "./Select";
+
+type AbilitiesSelectProps = Omit<SelectProps, "options" | "onChange"> & {
+ ability?: string;
+ onChange?: (
+ selections: {
+ value: string;
+ label: string;
+ }[]
+ ) => void;
+};
+
+const Abilities = ({
+ name,
+ label = "Abilities",
+ ability,
+ helperText,
+ isLoading,
+ isReadOnly,
+ placeholder = "Select Abilities",
+ onChange,
+ ...props
+}: AbilitiesSelectProps) => {
+ const { error } = useField(name);
+ const [value, setValue] = useControlField<string[]>(name);
+
+ const abilityFetcher =
+ useFetcher<Awaited<ReturnType<typeof getAbilitiesList>>>();
+
+ useEffect(() => {
+ abilityFetcher.load(`/api/resources/abilities`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const options = useMemo(
+ () =>
+ abilityFetcher.data?.data
+ ? abilityFetcher.data?.data.map((c) => ({
+ value: c.id,
+ label: c.name,
+ }))
+ : [],
+ [abilityFetcher.data]
+ );
+
+ const handleChange = (
+ selections: {
+ value: string;
+ label: string;
+ }[]
+ ) => {
+ const newValue = selections.map((s) => s.value as string) || [];
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selections);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options?.filter((option) => value?.includes(option.value)) ?? [],
+ [value, options]
+ );
+
+ // TODO: hack for default value
+ return abilityFetcher.state !== "loading" ? (
+ <FormControl isInvalid={!!error}>
+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {value.map((selection, index) => (
+ <input
+ key={`${name}[${index}]`}
+ type="hidden"
+ name={`${name}[${index}]`}
+ value={selection}
+ />
+ ))}
+ <Select
+ {...props}
+ isMulti
+ value={controlledValue}
+ isLoading={isLoading}
+ options={options}
+ placeholder={placeholder}
+ // @ts-ignore
+ onChange={handleChange}
+ />
+ {error ? (
+ <FormErrorMessage>{error}</FormErrorMessage>
+ ) : (
+ helperText && <FormHelperText>{helperText}</FormHelperText>
+ )}
+ </FormControl>
+ ) : (
+ <Box>
+ {label && <FormLabel>{label}</FormLabel>}
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ //@ts-ignore
+ />
+ </Box>
+ );
+};
+
+Abilities.displayName = "Abilities";
+
+export default Abilities;
diff --git a/apps/carbon/app/components/Form/Ability.tsx b/apps/carbon/app/components/Form/Ability.tsx
index 25397fb801..4efd52165d 100644
--- a/apps/carbon/app/components/Form/Ability.tsx
+++ b/apps/carbon/app/components/Form/Ability.tsx
@@ -8,66 +8,85 @@ import {
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
-import { useField } from "remix-validated-form";
+import { useControlField, useField } from "remix-validated-form";
import type { getAbilitiesList } from "~/modules/resources";
-import { mapRowsToOptions } from "~/utils/form";
import type { SelectProps } from "./Select";
-type AbilitySelectProps = Omit<SelectProps, "options">;
+type AbilitySelectProps = Omit<SelectProps, "options"> & {
+ ability?: string;
+};
const Ability = ({
name,
label = "Ability",
+ ability,
helperText,
isLoading,
isReadOnly,
- placeholder,
+ placeholder = "Select Ability",
onChange,
...props
}: AbilitySelectProps) => {
- const { getInputProps, error, defaultValue } = useField(name);
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
const abilityFetcher =
useFetcher<Awaited<ReturnType<typeof getAbilitiesList>>>();
useEffect(() => {
- if (abilityFetcher.type === "init") {
- abilityFetcher.load("/api/resources/abilities");
- }
- }, [abilityFetcher]);
+ abilityFetcher.load(`/api/resources/abilities`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
const options = useMemo(
() =>
- mapRowsToOptions({
- data: abilityFetcher.data?.data,
- value: "id",
- label: "name",
- }),
+ abilityFetcher.data?.data
+ ? abilityFetcher.data?.data.map((c) => ({
+ value: c.id,
+ label: c.name,
+ }))
+ : [],
[abilityFetcher.data]
);
- const initialValue = useMemo(
- () => options.filter((option) => option.value === defaultValue),
- [defaultValue, options]
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selection);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [value, options]
);
+ // so that we can call onChange on load
+ useEffect(() => {
+ if (controlledValue && controlledValue.value === defaultValue) {
+ handleChange(controlledValue);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [controlledValue?.value]);
+
// TODO: hack for default value
return abilityFetcher.state !== "loading" ? (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <input type="hidden" name={name} id={name} value={value} />
<Select
- {...getInputProps({
- // @ts-ignore
- id: name,
- })}
{...props}
- defaultValue={initialValue}
- isReadOnly={isReadOnly}
+ value={controlledValue}
isLoading={isLoading}
options={options}
placeholder={placeholder}
// @ts-ignore
- onChange={onChange ?? undefined}
+ onChange={handleChange}
/>
{error ? (
<FormErrorMessage>{error}</FormErrorMessage>
@@ -78,7 +97,12 @@ const Ability = ({
) : (
<Box>
{label && <FormLabel>{label}</FormLabel>}
- <Select isDisabled isLoading options={[]} />
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ //@ts-ignore
+ />
</Box>
);
};
diff --git a/apps/carbon/app/components/Form/Customer.tsx b/apps/carbon/app/components/Form/Customer.tsx
index f4afcf815d..661cae6213 100644
--- a/apps/carbon/app/components/Form/Customer.tsx
+++ b/apps/carbon/app/components/Form/Customer.tsx
@@ -8,7 +8,7 @@ import {
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
-import { useField } from "remix-validated-form";
+import { useControlField, useField } from "remix-validated-form";
import type { getCustomersList } from "~/modules/sales";
import { mapRowsToOptions } from "~/utils/form";
import type { SelectProps } from "./Select";
@@ -21,11 +21,12 @@ const Customer = ({
helperText,
isLoading,
isReadOnly,
- placeholder,
+ placeholder = "Select Customer",
onChange,
...props
}: CustomerSelectProps) => {
const { getInputProps, error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
const customerFetcher =
useFetcher<Awaited<ReturnType<typeof getCustomersList>>>();
@@ -46,11 +47,31 @@ const Customer = ({
[customerFetcher.data]
);
- const initialValue = useMemo(
- () => options.filter((option) => option.value === defaultValue),
- [defaultValue, options]
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selection);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [value, options]
);
+ // so that we can call onChange on load
+ useEffect(() => {
+ if (controlledValue && controlledValue.value === defaultValue) {
+ handleChange(controlledValue);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [controlledValue?.value]);
+
// TODO: hack for default value
return customerFetcher.state !== "loading" ? (
<FormControl isInvalid={!!error}>
@@ -61,13 +82,14 @@ const Customer = ({
id: name,
})}
{...props}
- defaultValue={initialValue}
- isReadOnly={isReadOnly}
+ value={controlledValue}
isLoading={isLoading}
options={options}
placeholder={placeholder}
// @ts-ignore
- onChange={onChange ?? undefined}
+ w="full"
+ isReadOnly={isReadOnly}
+ onChange={handleChange}
/>
{error ? (
<FormErrorMessage>{error}</FormErrorMessage>
@@ -78,7 +100,13 @@ const Customer = ({
) : (
<Box>
{label && <FormLabel>{label}</FormLabel>}
- <Select isDisabled isLoading options={[]} />
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ // @ts-ignore
+ w="full"
+ />
</Box>
);
};
diff --git a/apps/carbon/app/components/Form/Department.tsx b/apps/carbon/app/components/Form/Department.tsx
index 1718ec2392..0cc715f0e3 100644
--- a/apps/carbon/app/components/Form/Department.tsx
+++ b/apps/carbon/app/components/Form/Department.tsx
@@ -8,66 +8,85 @@ import {
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
-import { useField } from "remix-validated-form";
+import { useControlField, useField } from "remix-validated-form";
import type { getDepartmentsList } from "~/modules/resources";
-import { mapRowsToOptions } from "~/utils/form";
import type { SelectProps } from "./Select";
-type DepartmentSelectProps = Omit<SelectProps, "options">;
+type DepartmentSelectProps = Omit<SelectProps, "options"> & {
+ department?: string;
+};
const Department = ({
name,
label = "Department",
+ department,
helperText,
isLoading,
isReadOnly,
- placeholder,
+ placeholder = "Select Department",
onChange,
...props
}: DepartmentSelectProps) => {
- const { getInputProps, error, defaultValue } = useField(name);
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
const departmentFetcher =
useFetcher<Awaited<ReturnType<typeof getDepartmentsList>>>();
useEffect(() => {
- if (departmentFetcher.type === "init") {
- departmentFetcher.load("/api/resources/departments");
- }
- }, [departmentFetcher]);
+ departmentFetcher.load(`/api/resources/departments`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
const options = useMemo(
() =>
- mapRowsToOptions({
- data: departmentFetcher.data?.data,
- value: "id",
- label: "name",
- }),
+ departmentFetcher.data?.data
+ ? departmentFetcher.data?.data.map((c) => ({
+ value: c.id,
+ label: c.name,
+ }))
+ : [],
[departmentFetcher.data]
);
- const initialValue = useMemo(
- () => options.filter((option) => option.value === defaultValue),
- [defaultValue, options]
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selection);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [value, options]
);
+ // so that we can call onChange on load
+ useEffect(() => {
+ if (controlledValue && controlledValue.value === defaultValue) {
+ handleChange(controlledValue);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [controlledValue?.value]);
+
// TODO: hack for default value
return departmentFetcher.state !== "loading" ? (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <input type="hidden" name={name} id={name} value={value} />
<Select
- {...getInputProps({
- // @ts-ignore
- id: name,
- })}
{...props}
- defaultValue={initialValue}
- isReadOnly={isReadOnly}
+ value={controlledValue}
isLoading={isLoading}
options={options}
placeholder={placeholder}
// @ts-ignore
- onChange={onChange ?? undefined}
+ onChange={handleChange}
/>
{error ? (
<FormErrorMessage>{error}</FormErrorMessage>
@@ -78,7 +97,12 @@ const Department = ({
) : (
<Box>
{label && <FormLabel>{label}</FormLabel>}
- <Select isDisabled isLoading options={[]} />
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ //@ts-ignore
+ />
</Box>
);
};
diff --git a/apps/carbon/app/components/Form/Location.tsx b/apps/carbon/app/components/Form/Location.tsx
index ae8530dbe1..957753fd30 100644
--- a/apps/carbon/app/components/Form/Location.tsx
+++ b/apps/carbon/app/components/Form/Location.tsx
@@ -8,66 +8,85 @@ import {
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
-import { useField } from "remix-validated-form";
-import type { getLocationsList } from "~/modules/resources";
-import { mapRowsToOptions } from "~/utils/form";
+import { useControlField, useField } from "remix-validated-form";
+import type { getLocations } from "~/modules/resources";
import type { SelectProps } from "./Select";
-type LocationSelectProps = Omit<SelectProps, "options">;
+type LocationSelectProps = Omit<SelectProps, "options"> & {
+ location?: string;
+};
const Location = ({
name,
label = "Location",
+ location,
helperText,
isLoading,
isReadOnly,
- placeholder,
+ placeholder = "Select Location",
onChange,
...props
}: LocationSelectProps) => {
- const { getInputProps, error, defaultValue } = useField(name);
+ const { error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
const locationFetcher =
- useFetcher<Awaited<ReturnType<typeof getLocationsList>>>();
+ useFetcher<Awaited<ReturnType<typeof getLocations>>>();
useEffect(() => {
- if (locationFetcher.type === "init") {
- locationFetcher.load("/api/resources/locations");
- }
- }, [locationFetcher]);
+ locationFetcher.load(`/api/resources/locations`);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
const options = useMemo(
() =>
- mapRowsToOptions({
- data: locationFetcher.data?.data,
- value: "id",
- label: "name",
- }),
+ locationFetcher.data?.data
+ ? locationFetcher.data?.data.map((c) => ({
+ value: c.id,
+ label: c.name,
+ }))
+ : [],
[locationFetcher.data]
);
- const initialValue = useMemo(
- () => options.filter((option) => option.value === defaultValue),
- [defaultValue, options]
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selection);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [value, options]
);
+ // so that we can call onChange on load
+ useEffect(() => {
+ if (controlledValue && controlledValue.value === defaultValue) {
+ handleChange(controlledValue);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [controlledValue?.value]);
+
// TODO: hack for default value
return locationFetcher.state !== "loading" ? (
<FormControl isInvalid={!!error}>
{label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ <input type="hidden" name={name} id={name} value={value} />
<Select
- {...getInputProps({
- // @ts-ignore
- id: name,
- })}
{...props}
- defaultValue={initialValue}
- isReadOnly={isReadOnly}
+ value={controlledValue}
isLoading={isLoading}
options={options}
placeholder={placeholder}
// @ts-ignore
- onChange={onChange ?? undefined}
+ onChange={handleChange}
/>
{error ? (
<FormErrorMessage>{error}</FormErrorMessage>
@@ -78,7 +97,12 @@ const Location = ({
) : (
<Box>
{label && <FormLabel>{label}</FormLabel>}
- <Select isDisabled isLoading options={[]} />
+ <Select
+ isDisabled
+ isLoading={isLoading}
+ options={[]}
+ //@ts-ignore
+ />
</Box>
);
};
diff --git a/apps/carbon/app/components/Form/Supplier.tsx b/apps/carbon/app/components/Form/Supplier.tsx
index e893daa8ed..8005cc77a7 100644
--- a/apps/carbon/app/components/Form/Supplier.tsx
+++ b/apps/carbon/app/components/Form/Supplier.tsx
@@ -8,7 +8,7 @@ import {
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
import { useEffect, useMemo } from "react";
-import { useField } from "remix-validated-form";
+import { useControlField, useField } from "remix-validated-form";
import type { getSuppliersList } from "~/modules/purchasing";
import { mapRowsToOptions } from "~/utils/form";
import type { SelectProps } from "./Select";
@@ -26,6 +26,7 @@ const Supplier = ({
...props
}: SupplierSelectProps) => {
const { getInputProps, error, defaultValue } = useField(name);
+ const [value, setValue] = useControlField<string | undefined>(name);
const supplierFetcher =
useFetcher<Awaited<ReturnType<typeof getSuppliersList>>>();
@@ -46,11 +47,31 @@ const Supplier = ({
[supplierFetcher.data]
);
- const initialValue = useMemo(
- () => options.filter((option) => option.value === defaultValue),
- [defaultValue, options]
+ const handleChange = (selection: {
+ value: string | number;
+ label: string;
+ }) => {
+ const newValue = (selection.value as string) || undefined;
+ setValue(newValue);
+ if (onChange && typeof onChange === "function") {
+ onChange(selection);
+ }
+ };
+
+ const controlledValue = useMemo(
+ // @ts-ignore
+ () => options.find((option) => option.value === value),
+ [value, options]
);
+ // so that we can call onChange on load
+ useEffect(() => {
+ if (controlledValue && controlledValue.value === defaultValue) {
+ handleChange(controlledValue);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [controlledValue?.value]);
+
// TODO: hack for default value
return supplierFetcher.state !== "loading" ? (
<FormControl isInvalid={!!error}>
@@ -61,14 +82,14 @@ const Supplier = ({
id: name,
})}
{...props}
- defaultValue={initialValue}
- isReadOnly={isReadOnly}
+ value={controlledValue}
isLoading={isLoading}
options={options}
placeholder={placeholder}
- w="full"
// @ts-ignore
- onChange={onChange ?? undefined}
+ w="full"
+ isReadOnly={isReadOnly}
+ onChange={handleChange}
/>
{error ? (
<FormErrorMessage>{error}</FormErrorMessage>
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index 1afb464684..767654b4b9 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -1,3 +1,4 @@
+import Abilities from "./Abilities";
import Ability from "./Ability";
import Array from "./Array";
import Boolean from "./Boolean";
@@ -28,6 +29,7 @@ import User from "./User";
import Users from "./Users";
export {
+ Abilities,
Ability,
Array,
Boolean,
diff --git a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
index 4dd229bad4..43a3657e1f 100644
--- a/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx
@@ -88,6 +88,11 @@ export default function useBreadcrumbs(): Route[] {
name: "Locations",
to: match.pathname,
});
+ case "routes/x+/resources+/partners":
+ return acc.concat({
+ name: "Partners",
+ to: match.pathname,
+ });
case "routes/x+/resources+/people":
return acc.concat({
name: "People",
diff --git a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierContacts.tsx b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierContacts.tsx
index 7edcc1f155..9ba175e121 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierContacts.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierContacts.tsx
@@ -10,8 +10,9 @@ import {
useDisclosure,
} from "@chakra-ui/react";
import { useNavigate, useParams } from "@remix-run/react";
-import { useState } from "react";
-import { IoMdAdd } from "react-icons/io";
+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";
@@ -42,6 +43,59 @@ const SupplierContacts = ({
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}>
@@ -74,31 +128,7 @@ const SupplierContacts = ({
<Contact
contact={contact.contact}
user={contact.user}
- onDelete={
- permissions.can("delete", "purchasing")
- ? () => {
- setContact(contact);
- deleteContactModal.onOpen();
- }
- : undefined
- }
- onEdit={
- permissions.can("update", "purchasing")
- ? () => {
- setContact(contact);
- contactDrawer.onOpen();
- }
- : undefined
- }
- onCreateAccount={
- permissions.can("create", "users") &&
- contact.user === null
- ? () =>
- navigate(
- `/x/users/suppliers/new?id=${contact.id}&supplier=${supplierId}`
- )
- : undefined
- }
+ actions={getActions(contact)}
/>
) : null}
</ListItem>
diff --git a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierLocations.tsx b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierLocations.tsx
index 36fb15e3e1..48dc49b6ff 100644
--- a/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierLocations.tsx
+++ b/apps/carbon/app/modules/purchasing/interfaces/Suppliers/SupplierForm/components/SupplierLocations.tsx
@@ -9,9 +9,10 @@ import {
VStack,
useDisclosure,
} from "@chakra-ui/react";
-import { useParams } from "@remix-run/react";
-import { useState } from "react";
-import { IoMdAdd } from "react-icons/io";
+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";
@@ -27,6 +28,7 @@ const SupplierLocations = ({
locations = [],
isEditing = false,
}: SupplierLocationProps) => {
+ const navigate = useNavigate();
const permissions = usePermissions();
const locationDrawer = useDisclosure();
const deleteContactModal = useDisclosure();
@@ -39,6 +41,45 @@ const SupplierLocations = ({
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}>
@@ -68,22 +109,7 @@ const SupplierLocations = ({
{location.address && !Array.isArray(location.address) ? (
<Address
address={location.address}
- onDelete={
- permissions.can("delete", "purchasing")
- ? () => {
- setLocation(location);
- deleteContactModal.onOpen();
- }
- : undefined
- }
- onEdit={
- permissions.can("update", "purchasing")
- ? () => {
- setLocation(location);
- locationDrawer.onOpen();
- }
- : undefined
- }
+ actions={getActions(location)}
/>
) : null}
</ListItem>
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/ContractorForm.tsx b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/ContractorForm.tsx
new file mode 100644
index 0000000000..83ae4d3668
--- /dev/null
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/ContractorForm.tsx
@@ -0,0 +1,175 @@
+import { Select } from "@carbon/react";
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerOverlay,
+ FormControl,
+ FormErrorMessage,
+ FormLabel,
+ HStack,
+ VStack,
+} from "@chakra-ui/react";
+import { useFetcher, useNavigate } from "@remix-run/react";
+import { useEffect, useMemo } from "react";
+import { useControlField, useField, ValidatedForm } from "remix-validated-form";
+import { Abilities, Number, Submit, Supplier } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import type { getSupplierContacts } from "~/modules/purchasing";
+import { contractorValidator } from "~/modules/resources";
+import type { TypeOfValidator } from "~/types/validators";
+import { mapRowsToOptions } from "~/utils/form";
+
+type ContractorFormProps = {
+ initialValues: TypeOfValidator<typeof contractorValidator>;
+};
+
+const ContractorForm = ({ initialValues }: ContractorFormProps) => {
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const onClose = () => navigate(-1);
+
+ const isEditing = initialValues.id !== "";
+ const isDisabled = isEditing
+ ? !permissions.can("update", "resources")
+ : !permissions.can("create", "resources");
+
+ const supplierContactsFetcher =
+ useFetcher<Awaited<ReturnType<typeof getSupplierContacts>>>();
+
+ const onSupplierChange = ({ value }: { value: string | number }) => {
+ if (value)
+ supplierContactsFetcher.load(
+ `/api/purchasing/supplier-contacts?supplierId=${value}`
+ );
+ };
+
+ useEffect(() => {
+ if (initialValues.supplierId)
+ supplierContactsFetcher.load(
+ `/api/purchasing/supplier-locations?supplierId=${initialValues.supplierId}`
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const supplierContacts = useMemo(
+ () =>
+ mapRowsToOptions({
+ data: supplierContactsFetcher.data?.data ?? [],
+ value: "id",
+ // @ts-ignore
+ label: (row) => `${row.contact.firstName} ${row.contact.lastName}`,
+ }),
+ [supplierContactsFetcher.data]
+ );
+
+ return (
+ <Drawer onClose={onClose} isOpen={true} size="sm">
+ <ValidatedForm
+ validator={contractorValidator}
+ method="post"
+ action={
+ isEditing
+ ? `/x/resources/contractors/${initialValues.id}`
+ : "/x/resources/contractors/new"
+ }
+ defaultValues={initialValues}
+ >
+ <DrawerOverlay />
+ <DrawerContent>
+ <DrawerCloseButton />
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Contractor</DrawerHeader>
+ <DrawerBody pb={8}>
+ <VStack spacing={4} alignItems="start">
+ <Supplier
+ name="supplierId"
+ label="Supplier"
+ isReadOnly={isEditing}
+ onChange={onSupplierChange}
+ />
+ <SupplierContactsBySupplier
+ supplierContacts={supplierContacts}
+ initialContact={initialValues.id}
+ isReadOnly={isEditing}
+ />
+ <Abilities name="abilities" label="Abilities" />
+ <Number
+ name="hoursPerWeek"
+ label="Hours per Week"
+ helperText="The number of hours per week the supplier is available to work."
+ min={0}
+ max={10000}
+ />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack spacing={2}>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button
+ size="md"
+ colorScheme="gray"
+ variant="solid"
+ onClick={onClose}
+ >
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </DrawerContent>
+ </ValidatedForm>
+ </Drawer>
+ );
+};
+const SUPPLIER_CONTACT_FIELD = "id";
+
+const SupplierContactsBySupplier = ({
+ supplierContacts,
+ initialContact,
+ isReadOnly,
+}: {
+ supplierContacts: { value: string | number; label: string }[];
+ initialContact?: string;
+ isReadOnly: boolean;
+}) => {
+ const { error, getInputProps } = useField(SUPPLIER_CONTACT_FIELD);
+
+ const [supplierContact, setSupplierContact] = useControlField<{
+ value: string | number;
+ label: string;
+ } | null>(SUPPLIER_CONTACT_FIELD);
+
+ useEffect(() => {
+ // if the initial value is in the options, set it, otherwise set to null
+ if (supplierContacts) {
+ setSupplierContact(
+ supplierContacts.find((s) => s.value === initialContact) ?? null
+ );
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [supplierContacts, initialContact]);
+
+ return (
+ <FormControl isInvalid={!!error}>
+ <FormLabel htmlFor={SUPPLIER_CONTACT_FIELD}>Supplier Contact</FormLabel>
+ <Select
+ {...getInputProps({
+ // @ts-ignore
+ id: SUPPLIER_CONTACT_FIELD,
+ })}
+ options={supplierContacts}
+ value={supplierContact}
+ onChange={setSupplierContact}
+ // @ts-ignore
+ isReadOnly={isReadOnly}
+ w="full"
+ />
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
+ </FormControl>
+ );
+};
+
+export default ContractorForm;
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/index.ts b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/index.ts
new file mode 100644
index 0000000000..975f32c82c
--- /dev/null
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorForm/index.ts
@@ -0,0 +1,3 @@
+import ContractorForm from "./ContractorForm";
+
+export default ContractorForm;
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTable/ContractorsTable.tsx b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTable/ContractorsTable.tsx
new file mode 100644
index 0000000000..3b5420ead1
--- /dev/null
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTable/ContractorsTable.tsx
@@ -0,0 +1,104 @@
+import { Avatar, HStack, Link, MenuItem } from "@chakra-ui/react";
+import { useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { BsPencilSquare } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Contractor } from "~/modules/resources";
+
+type ContractorsTableProps = {
+ data: Contractor[];
+ count: number;
+};
+
+const ContractorsTable = memo(({ data, count }: ContractorsTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [params] = useUrlParams();
+
+ const rows = data.map((row) => ({
+ ...row,
+ }));
+
+ const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
+ return [
+ {
+ accessorKey: "supplier",
+ header: "Supplier",
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <Avatar size="sm" name={row.original.supplierName ?? ""} />
+
+ <Link
+ onClick={() => {
+ navigate(`/x/purchasing/suppliers/${row?.original.supplierId}`);
+ }}
+ >
+ {row.original.supplierName}
+ </Link>
+ </HStack>
+ ),
+ },
+ {
+ header: "Contractor",
+ cell: ({ row }) => (
+ <>{`${row.original.firstName} ${row.original.lastName}`}</>
+ ),
+ },
+ {
+ accessorKey: "hoursPerWeek",
+ header: "Hours per Week",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ }, [navigate]);
+
+ const renderContextMenu = useCallback(
+ (row: typeof rows[number]) => {
+ return (
+ <>
+ <MenuItem
+ icon={<BsPencilSquare />}
+ onClick={() => {
+ navigate(
+ `/x/resources/contractors/${
+ row.supplierContactId
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Edit Contractor
+ </MenuItem>
+ <MenuItem
+ isDisabled={!permissions.can("delete", "resources")}
+ icon={<IoMdTrash />}
+ onClick={() => {
+ navigate(
+ `/x/resources/contractors/delete/${
+ row.supplierContactId
+ }?${params.toString()}`
+ );
+ }}
+ >
+ Delete Contractor
+ </MenuItem>
+ </>
+ );
+ },
+ [navigate, params, permissions]
+ );
+
+ return (
+ <Table<typeof rows[number]>
+ data={rows}
+ count={count}
+ columns={columns}
+ renderContextMenu={renderContextMenu}
+ />
+ );
+});
+
+ContractorsTable.displayName = "ContractorsTable";
+export default ContractorsTable;
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTable/index.ts b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTable/index.ts
new file mode 100644
index 0000000000..f289ce4e4d
--- /dev/null
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTable/index.ts
@@ -0,0 +1,3 @@
+import ContractorsTable from "./ContractorsTable";
+
+export default ContractorsTable;
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/ContractorsTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/ContractorsTableFilters.tsx
new file mode 100644
index 0000000000..999d9d64a9
--- /dev/null
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/ContractorsTableFilters.tsx
@@ -0,0 +1,75 @@
+import { Select, useColor } from "@carbon/react";
+import { Button, HStack } from "@chakra-ui/react";
+import { Link } from "@remix-run/react";
+import { IoMdAdd } from "react-icons/io";
+import { DebouncedInput } from "~/components/Search";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Ability } from "~/modules/resources/types";
+import { mapRowsToOptions } from "~/utils/form";
+
+type ContractorsTableFiltersProps = {
+ abilities: Partial<Ability>[];
+};
+
+const ContractorsTableFilters = ({
+ abilities,
+}: ContractorsTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
+ const permissions = usePermissions();
+ const abilitiesOptions = mapRowsToOptions({
+ data: abilities,
+ value: "id",
+ label: "name",
+ });
+ const borderColor = useColor("gray.200");
+
+ return (
+ <HStack
+ borderBottomColor={borderColor}
+ borderBottomStyle="solid"
+ borderBottomWidth={1}
+ justifyContent="space-between"
+ px={4}
+ py={3}
+ w="full"
+ >
+ <HStack spacing={2}>
+ <DebouncedInput
+ param="name"
+ size="sm"
+ minW={180}
+ placeholder="Filter by name"
+ />
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={abilitiesOptions.filter(
+ (type) => type.value === params.get("ability")
+ )}
+ isClearable
+ options={abilitiesOptions}
+ onChange={(selected) => {
+ setParams({ ability: selected?.value });
+ }}
+ aria-label="Ability"
+ minW={180}
+ placeholder="Ability"
+ />
+ </HStack>
+ <HStack spacing={2}>
+ {permissions.can("create", "resources") && (
+ <Button
+ as={Link}
+ to={`new?${params.toString()}`}
+ colorScheme="brand"
+ leftIcon={<IoMdAdd />}
+ >
+ New Contractor
+ </Button>
+ )}
+ </HStack>
+ </HStack>
+ );
+};
+
+export default ContractorsTableFilters;
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/index.ts b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/index.ts
new file mode 100644
index 0000000000..1fca445583
--- /dev/null
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/ContractorsTableFilters/index.ts
@@ -0,0 +1,3 @@
+import ContractorsTableFilters from "./ContractorsTableFilters";
+
+export default ContractorsTableFilters;
diff --git a/apps/carbon/app/modules/resources/interfaces/Contractors/index.ts b/apps/carbon/app/modules/resources/interfaces/Contractors/index.ts
new file mode 100644
index 0000000000..8dcba2e355
--- /dev/null
+++ b/apps/carbon/app/modules/resources/interfaces/Contractors/index.ts
@@ -0,0 +1,5 @@
+import ContractorsTable from "./ContractorsTable";
+import ContractorsTableFilters from "./ContractorsTableFilters";
+import ContractorForm from "./ContractorForm";
+
+export { ContractorsTable, ContractorsTableFilters, ContractorForm };
diff --git a/apps/carbon/app/modules/resources/interfaces/Partners/PartnerForm/PartnerForm.tsx b/apps/carbon/app/modules/resources/interfaces/Partners/PartnerForm/PartnerForm.tsx
index 27e02b8722..832c558fed 100644
--- a/apps/carbon/app/modules/resources/interfaces/Partners/PartnerForm/PartnerForm.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Partners/PartnerForm/PartnerForm.tsx
@@ -1,3 +1,4 @@
+import { Select } from "@carbon/react";
import {
Button,
Drawer,
@@ -7,21 +8,27 @@ import {
DrawerFooter,
DrawerHeader,
DrawerOverlay,
+ FormControl,
+ FormErrorMessage,
+ FormLabel,
HStack,
VStack,
} from "@chakra-ui/react";
-import { useNavigate } from "@remix-run/react";
-import { ValidatedForm } from "remix-validated-form";
-import { Number, Submit, Supplier } from "~/components/Form";
+import { useFetcher, useNavigate } from "@remix-run/react";
+import { useEffect, useMemo } from "react";
+import { useControlField, useField, ValidatedForm } from "remix-validated-form";
+import { Abilities, Number, Submit, Supplier } from "~/components/Form";
import { usePermissions } from "~/hooks";
+import type { getSupplierLocations } from "~/modules/purchasing";
import { partnerValidator } from "~/modules/resources";
import type { TypeOfValidator } from "~/types/validators";
+import { mapRowsToOptions } from "~/utils/form";
-type SupplierFormProps = {
+type PartnerFormProps = {
initialValues: TypeOfValidator<typeof partnerValidator>;
};
-const SupplierForm = ({ initialValues }: SupplierFormProps) => {
+const PartnerForm = ({ initialValues }: PartnerFormProps) => {
const permissions = usePermissions();
const navigate = useNavigate();
const onClose = () => navigate(-1);
@@ -31,6 +38,35 @@ const SupplierForm = ({ initialValues }: SupplierFormProps) => {
? !permissions.can("update", "resources")
: !permissions.can("create", "resources");
+ const supplierLocationFetcher =
+ useFetcher<Awaited<ReturnType<typeof getSupplierLocations>>>();
+
+ const onSupplierChange = ({ value }: { value: string | number }) => {
+ if (value)
+ supplierLocationFetcher.load(
+ `/api/purchasing/supplier-locations?supplierId=${value}`
+ );
+ };
+
+ useEffect(() => {
+ if (initialValues.supplierId)
+ supplierLocationFetcher.load(
+ `/api/purchasing/supplier-locations?supplierId=${initialValues.supplierId}`
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const supplierLocations = useMemo(
+ () =>
+ mapRowsToOptions({
+ data: supplierLocationFetcher.data?.data ?? [],
+ value: "id",
+ // @ts-ignore
+ label: (row) => `${row.address.city}, ${row.address.state}`,
+ }),
+ [supplierLocationFetcher.data]
+ );
+
return (
<Drawer onClose={onClose} isOpen={true} size="sm">
<ValidatedForm
@@ -46,10 +82,21 @@ const SupplierForm = ({ initialValues }: SupplierFormProps) => {
<DrawerOverlay />
<DrawerContent>
<DrawerCloseButton />
- <DrawerHeader>{isEditing ? "Edit" : "New"} Supplier</DrawerHeader>
+ <DrawerHeader>{isEditing ? "Edit" : "New"} Partner</DrawerHeader>
<DrawerBody pb={8}>
<VStack spacing={4} alignItems="start">
- <Supplier name="id" label="Supplier" />
+ <Supplier
+ name="supplierId"
+ label="Supplier"
+ isReadOnly={isEditing}
+ onChange={onSupplierChange}
+ />
+ <SupplierLocationsBySupplier
+ supplierLocations={supplierLocations}
+ initialLocation={initialValues.id}
+ isReadOnly={isEditing}
+ />
+ <Abilities name="abilities" label="Abilities" />
<Number
name="hoursPerWeek"
label="Hours per Week"
@@ -78,4 +125,52 @@ const SupplierForm = ({ initialValues }: SupplierFormProps) => {
);
};
-export default SupplierForm;
+const SUPPLIER_LOCATION_FIELD = "id";
+
+const SupplierLocationsBySupplier = ({
+ supplierLocations,
+ initialLocation,
+ isReadOnly,
+}: {
+ supplierLocations: { value: string | number; label: string }[];
+ initialLocation?: string;
+ isReadOnly: boolean;
+}) => {
+ const { error, getInputProps } = useField(SUPPLIER_LOCATION_FIELD);
+
+ const [supplierLocation, setSupplierLocation] = useControlField<{
+ value: string | number;
+ label: string;
+ } | null>(SUPPLIER_LOCATION_FIELD);
+
+ useEffect(() => {
+ // if the initial value is in the options, set it, otherwise set to null
+ if (supplierLocations) {
+ setSupplierLocation(
+ supplierLocations.find((s) => s.value === initialLocation) ?? null
+ );
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [supplierLocations, initialLocation]);
+
+ return (
+ <FormControl isInvalid={!!error}>
+ <FormLabel htmlFor={SUPPLIER_LOCATION_FIELD}>Supplier Location</FormLabel>
+ <Select
+ {...getInputProps({
+ // @ts-ignore
+ id: SUPPLIER_LOCATION_FIELD,
+ })}
+ options={supplierLocations}
+ value={supplierLocation}
+ onChange={setSupplierLocation}
+ // @ts-ignore
+ isReadOnly={isReadOnly}
+ w="full"
+ />
+ {error && <FormErrorMessage>{error}</FormErrorMessage>}
+ </FormControl>
+ );
+};
+
+export default PartnerForm;
diff --git a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx
index 9bb5651549..51885cfbf7 100644
--- a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTable/PartnersTable.tsx
@@ -18,18 +18,9 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
const permissions = usePermissions();
const [params] = useUrlParams();
- const rows = data.map((row) => {
- if (Array.isArray(row.supplier)) {
- return {
- ...row,
- supplierName: row.supplier[0].name,
- };
- }
- return {
- ...row,
- supplierName: row.supplier?.name,
- };
- });
+ const rows = data.map((row) => ({
+ ...row,
+ }));
const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {
return [
@@ -38,11 +29,11 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
header: "Supplier",
cell: ({ row }) => (
<HStack spacing={2}>
- <Avatar size="sm" name={row.original.supplierName} />
+ <Avatar size="sm" name={row.original.supplierName ?? ""} />
<Link
onClick={() => {
- navigate(`/x/purchasing/suppliers/${row?.original.id}`);
+ navigate(`/x/purchasing/suppliers/${row?.original.supplierId}`);
}}
>
{row.original.supplierName}
@@ -50,6 +41,14 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
</HStack>
),
},
+ {
+ header: "Location",
+ cell: ({ row }) => (
+ <>
+ {row.original.city}, {row.original.state}
+ </>
+ ),
+ },
{
accessorKey: "hoursPerWeek",
header: "Hours per Week",
@@ -65,7 +64,11 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
<MenuItem
icon={<BsPencilSquare />}
onClick={() => {
- navigate(`/x/resources/partners/${row.id}?${params.toString()}`);
+ navigate(
+ `/x/resources/partners/${
+ row.supplierLocationId
+ }?${params.toString()}`
+ );
}}
>
Edit Partner
@@ -75,7 +78,9 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {
icon={<IoMdTrash />}
onClick={() => {
navigate(
- `/x/resources/partners/delete/${row.id}?${params.toString()}`
+ `/x/resources/partners/delete/${
+ row.supplierLocationId
+ }?${params.toString()}`
);
}}
>
diff --git a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx
index f232e137d9..00c5638261 100644
--- a/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Partners/PartnersTableFilters/PartnersTableFilters.tsx
@@ -1,13 +1,24 @@
-import { useColor } from "@carbon/react";
+import { Select, useColor } from "@carbon/react";
import { Button, HStack } from "@chakra-ui/react";
import { Link } from "@remix-run/react";
import { IoMdAdd } from "react-icons/io";
import { DebouncedInput } from "~/components/Search";
import { usePermissions, useUrlParams } from "~/hooks";
+import type { Ability } from "~/modules/resources/types";
+import { mapRowsToOptions } from "~/utils/form";
-const LocationsTableFilters = () => {
- const [params] = useUrlParams();
+type PartnersTableFiltersProps = {
+ abilities: Partial<Ability>[];
+};
+
+const PartnersTableFilters = ({ abilities }: PartnersTableFiltersProps) => {
+ const [params, setParams] = useUrlParams();
const permissions = usePermissions();
+ const abilitiesOptions = mapRowsToOptions({
+ data: abilities,
+ value: "id",
+ label: "name",
+ });
const borderColor = useColor("gray.200");
return (
@@ -27,6 +38,21 @@ const LocationsTableFilters = () => {
minW={180}
placeholder="Filter by name"
/>
+ <Select
+ // @ts-ignore
+ size="sm"
+ value={abilitiesOptions.filter(
+ (type) => type.value === params.get("ability")
+ )}
+ isClearable
+ options={abilitiesOptions}
+ onChange={(selected) => {
+ setParams({ ability: selected?.value });
+ }}
+ aria-label="Ability"
+ minW={180}
+ placeholder="Ability"
+ />
</HStack>
<HStack spacing={2}>
{permissions.can("create", "resources") && (
@@ -44,4 +70,4 @@ const LocationsTableFilters = () => {
);
};
-export default LocationsTableFilters;
+export default PartnersTableFilters;
diff --git a/apps/carbon/app/modules/resources/interfaces/Person/PersonJob/PersonJob.tsx b/apps/carbon/app/modules/resources/interfaces/Person/PersonJob/PersonJob.tsx
index 5ce0615457..7480f1a0c6 100644
--- a/apps/carbon/app/modules/resources/interfaces/Person/PersonJob/PersonJob.tsx
+++ b/apps/carbon/app/modules/resources/interfaces/Person/PersonJob/PersonJob.tsx
@@ -7,7 +7,7 @@ import {
VStack,
} from "@chakra-ui/react";
import { useFetcher } from "@remix-run/react";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo } from "react";
import { useControlField, useField, ValidatedForm } from "remix-validated-form";
import {
DatePicker,
@@ -29,18 +29,16 @@ type PersonJobProps = {
const PersonJob = ({ job }: PersonJobProps) => {
const shiftFetcher = useFetcher<Awaited<ReturnType<typeof getShiftsList>>>();
- const [location, setLocation] = useState<string | null>(
- job.locationId ?? null
- );
const onLocationChange = ({ value }: { value: string | number }) => {
- setLocation(value as string);
+ if (value) shiftFetcher.load(`/api/resources/shifts?location=${value}`);
};
useEffect(() => {
- shiftFetcher.load(`/api/resources/shifts?location=${location}`);
+ if (job.locationId)
+ shiftFetcher.load(`/api/resources/shifts?location=${job.locationId}`);
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [location]);
+ }, []);
const shifts = useMemo(
() =>
diff --git a/apps/carbon/app/modules/resources/interfaces/index.ts b/apps/carbon/app/modules/resources/interfaces/index.ts
index bf53725be1..ed44bba848 100644
--- a/apps/carbon/app/modules/resources/interfaces/index.ts
+++ b/apps/carbon/app/modules/resources/interfaces/index.ts
@@ -3,6 +3,7 @@ import useResourcesSidebar from "./useResourcesSidebar";
export { useResourcesSidebar };
export * from "./Abilities";
export * from "./Attributes";
+export * from "./Contractors";
export * from "./Departments";
export * from "./Equipment";
export * from "./Holidays";
diff --git a/apps/carbon/app/modules/resources/services/resources.form.ts b/apps/carbon/app/modules/resources/services/resources.form.ts
index ec9bb57f4d..ad26f3bd4c 100644
--- a/apps/carbon/app/modules/resources/services/resources.form.ts
+++ b/apps/carbon/app/modules/resources/services/resources.form.ts
@@ -74,6 +74,19 @@ export const attributeCategoryValidator = withZod(
})
);
+export const contractorValidator = withZod(
+ z.object({
+ id: z.string().min(20, { message: "Supplier Contact is required" }),
+ supplierId: z.string().min(20, { message: "Supplier is required" }),
+ hoursPerWeek: zfd.numeric(
+ z.number().min(0, { message: "Hours are required" })
+ ),
+ abilities: z
+ .array(z.string().min(20, { message: "Invalid ability" }))
+ .min(1, { message: "An ability is required" }),
+ })
+);
+
export const departmentValidator = withZod(
z.object({
id: zfd.text(z.string().optional()),
@@ -161,10 +174,14 @@ export const noteValidator = withZod(
export const partnerValidator = withZod(
z.object({
- id: z.string().min(36, { message: "Partner is required" }),
+ id: z.string().min(20, { message: "Supplier Location is required" }),
+ supplierId: z.string().min(20, { message: "Supplier is required" }),
hoursPerWeek: zfd.numeric(
z.number().min(0, { message: "Hours are required" })
),
+ abilities: z
+ .array(z.string().min(20, { message: "Invalid ability" }))
+ .min(1, { message: "An ability is required" }),
})
);
diff --git a/apps/carbon/app/modules/resources/services/resources.server.ts b/apps/carbon/app/modules/resources/services/resources.server.ts
index ab3fccc661..f50b5d24d6 100644
--- a/apps/carbon/app/modules/resources/services/resources.server.ts
+++ b/apps/carbon/app/modules/resources/services/resources.server.ts
@@ -35,6 +35,13 @@ export async function deleteAttributeCategory(
.eq("id", attributeCategoryId);
}
+export async function deleteContractor(
+ client: SupabaseClient<Database>,
+ contractorId: string
+) {
+ return client.from("contractor").delete().eq("id", contractorId);
+}
+
export async function deleteDepartment(
client: SupabaseClient<Database>,
departmentId: string
@@ -258,6 +265,38 @@ export async function getAttributeDataTypes(client: SupabaseClient<Database>) {
return client.from("attributeDataType").select("*");
}
+export async function getContractor(
+ client: SupabaseClient<Database>,
+ contractorId: string
+) {
+ return client
+ .from("contractors_query")
+ .select("*")
+ .eq("supplierContactId", contractorId)
+ .single();
+}
+
+export async function getContractors(
+ client: SupabaseClient<Database>,
+ args?: GenericQueryFilters & { name: string | null; ability: string | null }
+) {
+ let query = client.from("contractors_query").select("*").eq("active", true);
+
+ if (args?.name) {
+ query = query.ilike("supplierName", `%${args.name}%`);
+ }
+
+ if (args?.ability) {
+ query.contains("abilityIds", [args.ability]);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, "supplierName");
+ }
+
+ return query;
+}
+
export async function getDepartment(
client: SupabaseClient<Database>,
departmentId: string
@@ -481,27 +520,28 @@ export async function getPartner(
partnerId: string
) {
return client
- .from("partner")
- .select(`id, hoursPerWeek, supplier(name)`)
- .eq("id", partnerId)
+ .from("partners_query")
+ .select("*")
+ .eq("supplierLocationId", partnerId)
.single();
}
export async function getPartners(
client: SupabaseClient<Database>,
- args?: GenericQueryFilters & { name: string | null }
+ args?: GenericQueryFilters & { name: string | null; ability: string | null }
) {
- let query = client
- .from("partner")
- .select(`id, supplier(name), hoursPerWeek`, { count: "exact" })
- .eq("active", true);
+ let query = client.from("partners_query").select("*").eq("active", true);
if (args?.name) {
- query = query.ilike("name", `%${args.name}%`);
+ query = query.ilike("supplierName", `%${args.name}%`);
+ }
+
+ if (args?.ability) {
+ query.contains("abilityIds", [args.ability]);
}
if (args) {
- query = setGenericQueryFilters(query, args, "supplier(name)");
+ query = setGenericQueryFilters(query, args, "supplierName");
}
return query;
@@ -884,6 +924,59 @@ export async function updateAttributeSortOrder(
return Promise.all(updatePromises);
}
+export async function upsertContractor(
+ client: SupabaseClient<Database>,
+ contractorWithAbilities:
+ | {
+ id: string;
+ hoursPerWeek?: number;
+ abilities: string[];
+ createdBy: string;
+ }
+ | {
+ id: string;
+ hoursPerWeek?: number;
+ abilities: string[];
+ updatedBy: string;
+ }
+) {
+ const { abilities, ...contractor } = contractorWithAbilities;
+ if ("updatedBy" in contractor) {
+ const updateContractor = await client
+ .from("contractor")
+ .update(contractor)
+ .eq("id", contractor.id);
+ if (updateContractor.error) {
+ return updateContractor;
+ }
+ const deleteContractorAbilities = await client
+ .from("contractorAbility")
+ .delete()
+ .eq("contractorId", contractor.id);
+ if (deleteContractorAbilities.error) {
+ return deleteContractorAbilities;
+ }
+ } else {
+ const createContractor = await client
+ .from("contractor")
+ .insert([contractor]);
+ if (createContractor.error) {
+ return createContractor;
+ }
+ }
+
+ const contractorAbilities = abilities.map((ability) => {
+ return {
+ contractorId: contractor.id,
+ abilityId: ability,
+ createdBy:
+ "createdBy" in contractor ? contractor.createdBy : contractor.updatedBy,
+ };
+ });
+
+ return client.from("contractorAbility").insert(contractorAbilities);
+}
+
export async function upsertDepartment(
client: SupabaseClient<Database>,
department:
@@ -1073,22 +1166,52 @@ export async function upsertLocation(
export async function upsertPartner(
client: SupabaseClient<Database>,
- partner:
+ partnerWithAbilities:
| {
id: string;
hoursPerWeek?: number;
+ abilities: string[];
createdBy: string;
}
| {
id: string;
hoursPerWeek?: number;
+ abilities: string[];
updatedBy: string;
}
) {
+ const { abilities, ...partner } = partnerWithAbilities;
if ("updatedBy" in partner) {
- return client.from("partner").update(partner).eq("id", partner.id);
+ const updatePartner = await client
+ .from("partner")
+ .update(partner)
+ .eq("id", partner.id);
+ if (updatePartner.error) {
+ return updatePartner;
+ }
+ const deletePartnerAbilities = await client
+ .from("partnerAbility")
+ .delete()
+ .eq("partnerId", partner.id);
+ if (deletePartnerAbilities.error) {
+ return deletePartnerAbilities;
+ }
+ } else {
+ const createPartner = await client.from("partner").insert([partner]);
+ if (createPartner.error) {
+ return createPartner;
+ }
}
- return client.from("partner").insert([partner]);
+
+ const partnerAbilities = abilities.map((ability) => {
+ return {
+ partnerId: partner.id,
+ abilityId: ability,
+ createdBy: "createdBy" in partner ? partner.createdBy : partner.updatedBy,
+ };
+ });
+
+ return client.from("partnerAbility").insert(partnerAbilities);
}
export async function upsertShift(
@@ -1143,7 +1266,6 @@ export async function upsertWorkCell(
}
) {
if ("id" in workCell) {
- console.log("updating work cell", workCell);
const { id, ...update } = workCell;
return client
.from("workCell")
diff --git a/apps/carbon/app/modules/resources/types.ts b/apps/carbon/app/modules/resources/types.ts
index c16bdb2dea..85611b04a2 100644
--- a/apps/carbon/app/modules/resources/types.ts
+++ b/apps/carbon/app/modules/resources/types.ts
@@ -18,6 +18,7 @@ import type {
getWorkCellTypes,
getWorkCellType,
getHolidays,
+ getContractors,
} from "./services";
export type Ability = NonNullable<
@@ -78,6 +79,10 @@ export type AttributeDataType = {
isText: boolean;
};
+export type Contractor = NonNullable<
+ Awaited<ReturnType<typeof getContractors>>["data"]
+>[number];
+
export type Department = NonNullable<
Awaited<ReturnType<typeof getDepartments>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerContacts.tsx b/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerContacts.tsx
index e4f6246b9e..de3f0737c5 100644
--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerContacts.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerContacts.tsx
@@ -10,13 +10,14 @@ import {
useDisclosure,
} from "@chakra-ui/react";
import { useNavigate, useParams } from "@remix-run/react";
-import { useState } from "react";
-import { IoMdAdd } from "react-icons/io";
+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[];
@@ -42,6 +43,47 @@ const CustomerContacts = ({
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}>
@@ -74,31 +116,7 @@ const CustomerContacts = ({
<Contact
contact={contact.contact}
user={contact.user}
- onDelete={
- permissions.can("delete", "sales")
- ? () => {
- setContact(contact);
- deleteContactModal.onOpen();
- }
- : undefined
- }
- onEdit={
- permissions.can("update", "sales")
- ? () => {
- setContact(contact);
- contactDrawer.onOpen();
- }
- : undefined
- }
- onCreateAccount={
- permissions.can("create", "users") &&
- contact.user === null
- ? () =>
- navigate(
- `/x/users/customers/new?id=${contact.id}&customer=${customerId}`
- )
- : undefined
- }
+ actions={getActions(contact)}
/>
) : null}
</ListItem>
diff --git a/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerLocations.tsx b/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerLocations.tsx
index a1fcea0145..55679fca94 100644
--- a/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerLocations.tsx
+++ b/apps/carbon/app/modules/sales/interfaces/Customers/CustomerForm/components/CustomerLocations.tsx
@@ -10,8 +10,9 @@ import {
useDisclosure,
} from "@chakra-ui/react";
import { useParams } from "@remix-run/react";
-import { useState } from "react";
-import { IoMdAdd } from "react-icons/io";
+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";
@@ -39,6 +40,34 @@ const CustomerLocations = ({
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}>
@@ -68,22 +97,7 @@ const CustomerLocations = ({
{location.address && !Array.isArray(location.address) ? (
<Address
address={location.address}
- onDelete={
- permissions.can("delete", "sales")
- ? () => {
- setLocation(location);
- deleteContactModal.onOpen();
- }
- : undefined
- }
- onEdit={
- permissions.can("update", "sales")
- ? () => {
- setLocation(location);
- locationDrawer.onOpen();
- }
- : undefined
- }
+ actions={getActions(location)}
/>
) : null}
</ListItem>
diff --git a/apps/carbon/app/routes/api+/purchasing.supplier-locations.tsx b/apps/carbon/app/routes/api+/purchasing.supplier-locations.tsx
new file mode 100644
index 0000000000..db37b341f4
--- /dev/null
+++ b/apps/carbon/app/routes/api+/purchasing.supplier-locations.tsx
@@ -0,0 +1,34 @@
+import type { LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { requirePermissions } from "~/services/auth";
+import { getSupplierLocations } from "~/modules/purchasing";
+import { flash } from "~/services/session";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const authorized = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const supplierId = searchParams.get("supplierId") as string;
+
+ if (!supplierId || supplierId === "undefined")
+ return json({
+ data: [],
+ });
+
+ const locations = await getSupplierLocations(authorized.client, supplierId);
+ if (locations.error) {
+ return json(
+ locations,
+ await flash(
+ request,
+ error(locations.error, "Failed to get supplier locations")
+ )
+ );
+ }
+
+ return json(locations);
+}
diff --git a/apps/carbon/app/routes/x+/resources+/contractors.$supplierContactId.tsx b/apps/carbon/app/routes/x+/resources+/contractors.$supplierContactId.tsx
new file mode 100644
index 0000000000..2c6ddd4352
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/contractors.$supplierContactId.tsx
@@ -0,0 +1,90 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import {
+ ContractorForm,
+ contractorValidator,
+ getContractor,
+ upsertContractor,
+} from "~/modules/resources";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost, notFound } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "resources",
+ });
+
+ const { supplierContactId } = params;
+ if (!supplierContactId) throw notFound("Contractor ID was not found");
+
+ const contractor = await getContractor(client, supplierContactId);
+
+ if (contractor.error) {
+ return redirect(
+ "/x/resources/contractors",
+ await flash(request, error(contractor.error, "Failed to get contractor"))
+ );
+ }
+
+ return json({
+ contractor: contractor.data,
+ });
+}
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "resources",
+ });
+
+ const validation = await contractorValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, hoursPerWeek, abilities } = validation.data;
+ if (!id) throw notFound("Contractor ID was not found");
+
+ const updateContractor = await upsertContractor(client, {
+ id,
+ hoursPerWeek,
+ abilities,
+ updatedBy: userId,
+ });
+
+ if (updateContractor.error) {
+ return redirect(
+ "/x/resources/contractors",
+ await flash(
+ request,
+ error(updateContractor.error, "Failed to create contractor.")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/resources/contractors",
+ await flash(request, success("Contractor updated."))
+ );
+}
+
+export default function ContractorRoute() {
+ const { contractor } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: contractor.supplierContactId ?? "",
+ supplierId: contractor.supplierId ?? "",
+ hoursPerWeek: contractor.hoursPerWeek ?? 0,
+ abilities: contractor.abilityIds ?? ([] as string[]),
+ };
+
+ return <ContractorForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/resources+/contractors.delete.$supplierId.tsx b/apps/carbon/app/routes/x+/resources+/contractors.delete.$supplierId.tsx
new file mode 100644
index 0000000000..c92d0b520a
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/contractors.delete.$supplierId.tsx
@@ -0,0 +1,81 @@
+import type { ActionArgs, LoaderArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteContractor, getContractor } from "~/modules/resources";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { error, success } from "~/utils/result";
+import { notFound } from "~/utils/http";
+
+export async function loader({ request, params }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "resources",
+ role: "employee",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw notFound("supplierId not found");
+
+ const contractor = await getContractor(client, supplierId);
+ if (contractor.error) {
+ return redirect(
+ "/x/resources/contractors",
+ await flash(request, error(contractor.error, "Failed to get contractor"))
+ );
+ }
+
+ return json({
+ contractor: contractor.data,
+ });
+}
+
+export async function action({ request, params }: ActionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "resources",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) {
+ return redirect(
+ "/x/resources/contractors",
+ await flash(request, error(params, "Failed to get contractor id"))
+ );
+ }
+
+ const { error: deleteContractorError } = await deleteContractor(
+ client,
+ supplierId
+ );
+ if (deleteContractorError) {
+ return redirect(
+ "/x/resources/contractors",
+ await flash(
+ request,
+ error(deleteContractorError, "Failed to delete contractor")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/resources/contractors",
+ await flash(request, success("Successfully deleted contractor"))
+ );
+}
+
+export default function DeleteContractorRoute() {
+ const { contractor } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ const onCancel = () => navigate("/x/resources/contractors");
+
+ return (
+ <ConfirmDelete
+ action={`/x/resources/contractors/delete/${contractor.supplierContactId}`}
+ name={`${contractor.firstName} ${contractor.lastName}`}
+ text={`Are you sure you want to delete the contractor:
+ ${contractor.firstName} ${contractor.lastName}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/resources+/contractors.new.tsx b/apps/carbon/app/routes/x+/resources+/contractors.new.tsx
new file mode 100644
index 0000000000..25d7832c5d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/contractors.new.tsx
@@ -0,0 +1,64 @@
+import type { ActionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { validationError } from "remix-validated-form";
+import { useUrlParams } from "~/hooks";
+import {
+ ContractorForm,
+ contractorValidator,
+ upsertContractor,
+} from "~/modules/resources";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { assertIsPost } from "~/utils/http";
+import { error, success } from "~/utils/result";
+
+export async function action({ request }: ActionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "resources",
+ });
+
+ const validation = await contractorValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, hoursPerWeek, abilities } = validation.data;
+
+ const createContractor = await upsertContractor(client, {
+ id,
+ hoursPerWeek,
+ abilities,
+ createdBy: userId,
+ });
+
+ if (createContractor.error) {
+ return redirect(
+ "/x/resources/contractors",
+ await flash(
+ request,
+ error(createContractor.error, "Failed to create contractor.")
+ )
+ );
+ }
+
+ return redirect(
+ "/x/resources/contractors",
+ await flash(request, success("Contractor created."))
+ );
+}
+
+export default function NewContractorRoute() {
+ const [params] = useUrlParams();
+ const initialValues = {
+ id: params.get("id") ?? "",
+ supplierId: params.get("supplierId") ?? "",
+ hoursPerWeek: 0,
+ abilities: [] as string[],
+ };
+
+ return <ContractorForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/resources+/contractors.tsx b/apps/carbon/app/routes/x+/resources+/contractors.tsx
new file mode 100644
index 0000000000..4126579939
--- /dev/null
+++ b/apps/carbon/app/routes/x+/resources+/contractors.tsx
@@ -0,0 +1,67 @@
+import { VStack } from "@chakra-ui/react";
+import type { LoaderArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ ContractorsTable,
+ ContractorsTableFilters,
+ getContractors,
+ getAbilitiesList,
+} from "~/modules/resources";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session";
+import { getGenericQueryFilters } from "~/utils/query";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "resources",
+ role: "employee",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const name = searchParams.get("name");
+ const ability = searchParams.get("ability");
+ const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
+
+ const [contractors, abilities] = await Promise.all([
+ getContractors(client, {
+ name,
+ limit,
+ offset,
+ sorts,
+ ability,
+ }),
+ getAbilitiesList(client),
+ ]);
+
+ if (contractors.error) {
+ return redirect(
+ "/x/resources",
+ await flash(
+ request,
+ error(contractors.error, "Failed to load contractors")
+ )
+ );
+ }
+
+ return json({
+ contractors: contractors.data ?? [],
+ abilities: abilities.data ?? [],
+ count: contractors.count ?? 0,
+ });
+}
+
+export default function Route() {
+ const { contractors, abilities, count } = useLoaderData<typeof loader>();
+
+ return (
+ <VStack w="full" h="full" spacing={0}>
+ <ContractorsTableFilters abilities={abilities} />
+ <ContractorsTable data={contractors} count={count} />
+ <Outlet />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/resources+/partners.$supplierId.tsx b/apps/carbon/app/routes/x+/resources+/partners.$supplierLocationId.tsx
similarity index 81%
rename from apps/carbon/app/routes/x+/resources+/partners.$supplierId.tsx
rename to apps/carbon/app/routes/x+/resources+/partners.$supplierLocationId.tsx
index 4c34d4be82..4fe43fc0c1 100644
--- a/apps/carbon/app/routes/x+/resources+/partners.$supplierId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/partners.$supplierLocationId.tsx
@@ -19,10 +19,10 @@ export async function loader({ request, params }: LoaderArgs) {
view: "resources",
});
- const { supplierId } = params;
- if (!supplierId) throw notFound("Partner ID was not found");
+ const { supplierLocationId } = params;
+ if (!supplierLocationId) throw notFound("Partner ID was not found");
- const partner = await getPartner(client, supplierId);
+ const partner = await getPartner(client, supplierLocationId);
if (partner.error) {
return redirect(
@@ -48,12 +48,13 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const { id, hoursPerWeek } = validation.data;
+ const { id, hoursPerWeek, abilities } = validation.data;
if (!id) throw notFound("Partner ID was not found");
const updatePartner = await upsertPartner(client, {
id,
hoursPerWeek,
+ abilities,
updatedBy: userId,
});
@@ -77,8 +78,10 @@ export default function PartnerRoute() {
const { partner } = useLoaderData<typeof loader>();
const initialValues = {
- id: partner.id,
- hoursPerWeek: partner.hoursPerWeek,
+ id: partner.supplierLocationId ?? "",
+ supplierId: partner.supplierId ?? "",
+ hoursPerWeek: partner.hoursPerWeek ?? 0,
+ abilities: partner.abilityIds ?? ([] as string[]),
};
return <PartnerForm initialValues={initialValues} />;
diff --git a/apps/carbon/app/routes/x+/resources+/partners.delete.$supplierId.tsx b/apps/carbon/app/routes/x+/resources+/partners.delete.$supplierId.tsx
index 5bbb022d36..cc0363376a 100644
--- a/apps/carbon/app/routes/x+/resources+/partners.delete.$supplierId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/partners.delete.$supplierId.tsx
@@ -1,6 +1,6 @@
import type { ActionArgs, LoaderArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { useLoaderData, useNavigate } from "@remix-run/react";
import { ConfirmDelete } from "~/components/Modals";
import { deletePartner, getPartner } from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
@@ -61,22 +61,18 @@ export async function action({ request, params }: ActionArgs) {
}
export default function DeletePartnerRoute() {
- const { supplierId } = useParams();
const { partner } = useLoaderData<typeof loader>();
const navigate = useNavigate();
- if (!supplierId || !partner || !partner.supplier) return null;
- const name = Array.isArray(partner.supplier)
- ? partner.supplier[0].name
- : partner.supplier.name;
-
const onCancel = () => navigate("/x/resources/partners");
return (
<ConfirmDelete
- action={`/x/resources/partners/delete/${supplierId}`}
- name={name}
- text={`Are you sure you want to delete the partner: ${name}? This cannot be undone.`}
+ action={`/x/resources/partners/delete/${partner.supplierLocationId}`}
+ name={partner.supplierName ?? ""}
+ text={`Are you sure you want to delete the partner: ${
+ partner.supplierName ?? ""
+ }? This cannot be undone.`}
onCancel={onCancel}
/>
);
diff --git a/apps/carbon/app/routes/x+/resources+/partners.new.tsx b/apps/carbon/app/routes/x+/resources+/partners.new.tsx
index dacc72d17f..47e9530c66 100644
--- a/apps/carbon/app/routes/x+/resources+/partners.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/partners.new.tsx
@@ -1,6 +1,7 @@
import type { ActionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { validationError } from "remix-validated-form";
+import { useUrlParams } from "~/hooks";
import {
PartnerForm,
partnerValidator,
@@ -23,11 +24,12 @@ export async function action({ request }: ActionArgs) {
return validationError(validation.error);
}
- const { id, hoursPerWeek } = validation.data;
+ const { id, hoursPerWeek, abilities } = validation.data;
const createPartner = await upsertPartner(client, {
id,
hoursPerWeek,
+ abilities,
createdBy: userId,
});
@@ -48,9 +50,12 @@ export async function action({ request }: ActionArgs) {
}
export default function NewPartnerRoute() {
+ const [params] = useUrlParams();
const initialValues = {
- id: "",
+ id: params.get("id") ?? "",
+ supplierId: params.get("supplierId") ?? "",
hoursPerWeek: 0,
+ abilities: [] as string[],
};
return <PartnerForm initialValues={initialValues} />;
diff --git a/apps/carbon/app/routes/x+/resources+/partners.tsx b/apps/carbon/app/routes/x+/resources+/partners.tsx
index 26713723dd..b28366e8e8 100644
--- a/apps/carbon/app/routes/x+/resources+/partners.tsx
+++ b/apps/carbon/app/routes/x+/resources+/partners.tsx
@@ -7,6 +7,7 @@ import {
PartnersTable,
PartnersTableFilters,
getPartners,
+ getAbilitiesList,
} from "~/modules/resources";
import { requirePermissions } from "~/services/auth";
import { flash } from "~/services/session";
@@ -22,14 +23,19 @@ export async function loader({ request }: LoaderArgs) {
const url = new URL(request.url);
const searchParams = new URLSearchParams(url.search);
const name = searchParams.get("name");
+ const ability = searchParams.get("ability");
const { limit, offset, sorts } = getGenericQueryFilters(searchParams);
- const partners = await getPartners(client, {
- name,
- limit,
- offset,
- sorts,
- });
+ const [partners, abilities] = await Promise.all([
+ getPartners(client, {
+ name,
+ limit,
+ offset,
+ sorts,
+ ability,
+ }),
+ getAbilitiesList(client),
+ ]);
if (partners.error) {
return redirect(
@@ -40,16 +46,17 @@ export async function loader({ request }: LoaderArgs) {
return json({
partners: partners.data ?? [],
+ abilities: abilities.data ?? [],
count: partners.count ?? 0,
});
}
export default function Route() {
- const { partners, count } = useLoaderData<typeof loader>();
+ const { partners, abilities, count } = useLoaderData<typeof loader>();
return (
<VStack w="full" h="full" spacing={0}>
- <PartnersTableFilters />
+ <PartnersTableFilters abilities={abilities} />
<PartnersTable data={partners} count={count} />
<Outlet />
</VStack>
diff --git a/apps/carbon/app/types/index.ts b/apps/carbon/app/types/index.ts
index b02e21d426..7f1b5b50dc 100644
--- a/apps/carbon/app/types/index.ts
+++ b/apps/carbon/app/types/index.ts
@@ -3,6 +3,12 @@ import type { TypedResponse } from "@remix-run/node";
import type { ReactElement } from "react";
import type { ValidationErrorResponseData } from "remix-validated-form";
+export type Action = {
+ label: string;
+ icon: ReactElement;
+ onClick: () => void;
+};
+
export type Authenticated<T> = T & {
role?: Role;
permission?: string;
diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.ts
index 18631ffd5d..868f987b6e 100644
--- a/packages/carbon-database/src/types.ts
+++ b/packages/carbon-database/src/types.ts
@@ -170,6 +170,55 @@ export interface Database {
id?: string;
};
};
+ contractor: {
+ Row: {
+ id: string;
+ createdBy: string;
+ updatedBy: string | null;
+ updatedAt: string | null;
+ hoursPerWeek: number;
+ active: boolean;
+ createdAt: string;
+ };
+ Insert: {
+ id: string;
+ createdBy: string;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ hoursPerWeek?: number;
+ active?: boolean;
+ createdAt?: string;
+ };
+ Update: {
+ id?: string;
+ createdBy?: string;
+ updatedBy?: string | null;
+ updatedAt?: string | null;
+ hoursPerWeek?: number;
+ active?: boolean;
+ createdAt?: string;
+ };
+ };
+ contractorAbility: {
+ Row: {
+ contractorId: string;
+ abilityId: string;
+ createdBy: string;
+ createdAt: string;
+ };
+ Insert: {
+ contractorId: string;
+ abilityId: string;
+ createdBy: string;
+ createdAt?: string;
+ };
+ Update: {
+ contractorId?: string;
+ abilityId?: string;
+ createdBy?: string;
+ createdAt?: string;
+ };
+ };
country: {
Row: {
name: string;
@@ -821,6 +870,26 @@ export interface Database {
createdAt?: string;
};
};
+ partnerAbility: {
+ Row: {
+ partnerId: string;
+ abilityId: string;
+ createdBy: string;
+ createdAt: string;
+ };
+ Insert: {
+ partnerId: string;
+ abilityId: string;
+ createdBy: string;
+ createdAt?: string;
+ };
+ Update: {
+ partnerId?: string;
+ abilityId?: string;
+ createdBy?: string;
+ createdAt?: string;
+ };
+ };
search: {
Row: {
id: number;
@@ -1324,6 +1393,19 @@ export interface Database {
};
};
Views: {
+ contractors_query: {
+ Row: {
+ supplierContactId: string | null;
+ active: boolean | null;
+ hoursPerWeek: number | null;
+ supplierId: string | null;
+ supplierName: string | null;
+ firstName: string | null;
+ lastName: string | null;
+ email: string | null;
+ abilityIds: string[] | null;
+ };
+ };
group_member: {
Row: {
id: number | null;
@@ -1372,6 +1454,18 @@ export interface Database {
year: number | null;
};
};
+ partners_query: {
+ Row: {
+ supplierLocationId: string | null;
+ active: boolean | null;
+ hoursPerWeek: number | null;
+ supplierId: string | null;
+ supplierName: string | null;
+ city: string | null;
+ state: string | null;
+ abilityIds: string[] | null;
+ };
+ };
};
Functions: {
_xid_machine_id: {
diff --git a/packages/carbon-database/supabase/.branches/_current_branch b/packages/carbon-database/supabase/.branches/_current_branch
new file mode 100644
index 0000000000..88d050b190
--- /dev/null
+++ b/packages/carbon-database/supabase/.branches/_current_branch
@@ -0,0 +1 @@
+main
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/migrations/20230319224154_partners.sql b/packages/carbon-database/supabase/migrations/20230319224154_partners.sql
index bd23d71233..c3f598bc98 100644
--- a/packages/carbon-database/supabase/migrations/20230319224154_partners.sql
+++ b/packages/carbon-database/supabase/migrations/20230319224154_partners.sql
@@ -8,7 +8,42 @@ CREATE TABLE "partner" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
CONSTRAINT "partner_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "partner_id_fkey" FOREIGN KEY ("id") REFERENCES "supplier"("id"),
+ CONSTRAINT "partner_id_fkey" FOREIGN KEY ("id") REFERENCES "supplierLocation"("id"),
CONSTRAINT "partner_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
CONSTRAINT "partner_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
-);
\ No newline at end of file
+);
+
+CREATE TABLE "partnerAbility" (
+ "partnerId" TEXT NOT NULL,
+ "abilityId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "partnerAbility_pkey" PRIMARY KEY ("partnerId", "abilityId"),
+ CONSTRAINT "partnerAbility_partnerId_fkey" FOREIGN KEY ("partnerId") REFERENCES "partner"("id") ON DELETE CASCADE,
+ CONSTRAINT "partnerAbility_abilityId_fkey" FOREIGN KEY ("abilityId") REFERENCES "ability"("id") ON DELETE CASCADE,
+ CONSTRAINT "partnerAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
+);
+
+CREATE VIEW "partners_query" AS
+ SELECT
+ p.id AS "supplierLocationId",
+ p."active",
+ p."hoursPerWeek",
+ s.id AS "supplierId",
+ s.name AS "supplierName",
+ a.city,
+ a.state,
+ array_agg(pa."abilityId") AS "abilityIds"
+ FROM "partner" p
+ INNER JOIN "supplierLocation" sl
+ ON sl.id = p.id
+ INNER JOIN "supplier" s
+ ON s.id = sl."supplierId"
+ INNER JOIN "address" a
+ ON a.id = sl."addressId"
+ INNER JOIN "partnerAbility" pa
+ ON pa."partnerId" = p.id
+ WHERE p."active" = true
+ GROUP BY p.id, p.active, p."hoursPerWeek", s.id, a.id, s.name, a.city, a.state
+;
\ No newline at end of file
diff --git a/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
new file mode 100644
index 0000000000..c80c3722a4
--- /dev/null
+++ b/packages/carbon-database/supabase/migrations/20230329021751_contractors.sql
@@ -0,0 +1,50 @@
+CREATE TABLE "contractor" (
+ "id" TEXT NOT NULL,
+ "hoursPerWeek" INTEGER NOT NULL DEFAULT 0,
+ "active" BOOLEAN NOT NULL DEFAULT true,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+
+ CONSTRAINT "contractor_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "contractor_id_fkey" FOREIGN KEY ("id") REFERENCES "supplierContact"("id"),
+ CONSTRAINT "contractor_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id"),
+ CONSTRAINT "contractor_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
+);
+
+CREATE TABLE "contractorAbility" (
+ "contractorId" TEXT NOT NULL,
+ "abilityId" TEXT NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "contractorAbility_pkey" PRIMARY KEY ("contractorId", "abilityId"),
+ CONSTRAINT "contractorAbility_contractorId_fkey" FOREIGN KEY ("contractorId") REFERENCES "contractor"("id") ON DELETE CASCADE,
+ CONSTRAINT "contractorAbility_abilityId_fkey" FOREIGN KEY ("abilityId") REFERENCES "ability"("id") ON DELETE CASCADE,
+ CONSTRAINT "contractorAbility_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id")
+);
+
+CREATE VIEW "contractors_query" AS
+ SELECT
+ p.id AS "supplierContactId",
+ p."active",
+ p."hoursPerWeek",
+ s.id AS "supplierId",
+ s.name AS "supplierName",
+ c."firstName",
+ c."lastName",
+ c."email",
+ array_agg(pa."abilityId") AS "abilityIds"
+ FROM "contractor" p
+ INNER JOIN "supplierContact" sc
+ ON sc.id = p.id
+ INNER JOIN "supplier" s
+ ON s.id = sc."supplierId"
+ INNER JOIN "contact" c
+ ON c.id = sc."contactId"
+ INNER JOIN "contractorAbility" pa
+ ON pa."contractorId" = p.id
+ WHERE p."active" = true
+ GROUP BY p.id, p.active, p."hoursPerWeek", s.id, c.id, s.name, c."firstName", c."lastName", c."email"
+;
\ No newline at end of file
diff --git a/www/pages/docs/core-concepts/fetching.mdx b/www/pages/docs/core-concepts/fetching.mdx
index 68dbf15d6d..729c40206c 100644
--- a/www/pages/docs/core-concepts/fetching.mdx
+++ b/www/pages/docs/core-concepts/fetching.mdx
@@ -3,7 +3,7 @@ title: Data Fetching in Carbon ERP
description: Conventions for fetching data in Carbon ERP
---
-import { Callout } from "nextra-theme-docs";
+import { Callout, Tabs, Tab } from "nextra-theme-docs";
# Fetching
@@ -113,7 +113,57 @@ export async function getPartners(
}
```
+If a query becomes complex, the convention is to create a SQL view in the database and query that instead. Here's an example of a view that joins the `partner` and `supplier` tables:
+
+<Tabs
+ items={[
+ "SQL",
+ "TypeScript",
+ ]}
+>
+ <Tab>
+```sql
+CREATE VIEW "partners_query" AS
+ SELECT
+ p.id AS "supplierLocationId",
+ p."active",
+ p."hoursPerWeek",
+ s.id AS "supplierId",
+ s.name AS "supplierName",
+ a.city,
+ a.state,
+ array_agg(pa."abilityId") AS "abilityIds"
+ FROM "partner" p
+ INNER JOIN "supplierLocation" sl
+ ON sl.id = p.id
+ INNER JOIN "supplier" s
+ ON s.id = sl."supplierId"
+ INNER JOIN "address" a
+ ON a.id = sl."addressId"
+ INNER JOIN "partnerAbility" pa
+ ON pa."partnerId" = p.id
+ WHERE p."active" = true
+ GROUP BY p.id, p.active, p."hoursPerWeek", s.id, a.id, s.name, a.city, a.state
+;
+```
+ </Tab>
+ <Tab>
+```ts
+export async function getPartner(
+ client: SupabaseClient<Database>,
+ partnerId: string
+) {
+ return client
+ .from("partners_query")
+ .select("*")
+ .eq("supplierLocationId", partnerId)
+ .single();
+}
+```
+ </Tab>
+</Tabs>
<Callout>
For more information on query building, see the [Supabase
documentation](https://supabase.io/docs/reference/javascript/select)
</Callout>
+```
diff --git a/www/pages/docs/core-concepts/writing.mdx b/www/pages/docs/core-concepts/writing.mdx
index 5f23c42287..5c73c8ac1b 100644
--- a/www/pages/docs/core-concepts/writing.mdx
+++ b/www/pages/docs/core-concepts/writing.mdx
@@ -55,7 +55,7 @@ Here's an example of how they work together on the client-side:
```tsx
import { ValidatedForm } from "remix-validated-form";
-import { Boolean, Hidden, Input, Numeric} from "~/components/Form";
+import { Boolean, Hidden, Input, Numeric, Submit } from "~/components/Form";
import { personValidator } from "~/modules/people";
@@ -69,8 +69,9 @@ const Form = ({initialValues}: FormProps) => {
>
<Hidden name="id" />
<Input name="name" label="Name">
- <Numeric name="age" min={0} max={100} />
+ <Numeric name="age" min={0} />
<Boolean name="male" label="Male" />
+ <Submit>Save</Submit>
</ValidatedForm>
)
}
diff --git a/www/pages/docs/tech-stack.mdx b/www/pages/docs/tech-stack.mdx
index 43b69271f7..7faecc741d 100644
--- a/www/pages/docs/tech-stack.mdx
+++ b/www/pages/docs/tech-stack.mdx
@@ -27,16 +27,14 @@ We chose TypeScript because it allows us to use a single, strongly-typed languag
[React](https://reactjs.org) is a JavaScript library for building user interfaces. It's the most popular frontend framework in the world, and it's used by many of the biggest companies in the world, including Facebook, Netflix, and Airbnb.
-React is a component-based framework, which means that you can build your UI out of small, reusable components. This makes it easy to build complex UIs, and it also makes it easy to reuse code across different parts of your application.
-
-React is also declarative, which means that you describe what you want your UI to look like, and React will take care of updating the UI whenever the data changes. This makes it easy to build complex UIs, and it also makes it easy to reuse code across different parts of your application.
-
-We have a package called [@carbon/react](https://github.com/barbinbrad/carbon/tree/main/packages/carbon-react/src) that has a bunch of React components that you can use to build your UI. You can also use any other React component library that you want.
+We have a package called [@carbon/react](https://github.com/barbinbrad/carbon/tree/main/packages/carbon-react/src) that has a bunch of React pre-built components that you can use to build your UI. You can also use any other React component library.
## 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.
+Here's an example of a Chakra UI button:
+
```jsx
import { Button } from "@chakra-ui/react";
@@ -55,7 +53,7 @@ There are a lot of other component libraries out there, but we chose Chakra UI b
[Remix](https://remix.run) is a framework for building full-stack web applications. It's built on top of React, and it allows us to co-locate server-side code and client-side code in the same files. When combined with TypeScript and Supabase, this gives us type-safety from the database to the UI.
-Remix makes for a beautiful developer experience. It's use of [loaders, actions and components](https://remix.run/blog/remix-data-flow) **minimizes the amount of code that needs written while maximzing performance**. To learn more about Remix, check out their documentation, and take a look at some files from our [routes](https://github.com/barbinbrad/carbon/tree/main/apps/carbon/app/routes) directory.
+Remix makes for a beautiful developer experience. It's use of nested routes, [loaders, actions and components](https://remix.run/blog/remix-data-flow) **minimizes the amount of code that needs written while maximzing performance**. To learn more about Remix, check out their documentation, and take a look at some files from our [routes](https://github.com/barbinbrad/carbon/tree/main/apps/carbon/app/routes) directory.
Here's a slightly-simplified example of how a Remix route works: