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.

feat: onboarding

Brad Barbincbaacadc0984
diff --git a/apps/carbon/app/hooks/index.ts b/apps/carbon/app/hooks/index.ts
index 9b3b97ab4c..9988303e8c 100644
--- a/apps/carbon/app/hooks/index.ts
+++ b/apps/carbon/app/hooks/index.ts
@@ -1,5 +1,6 @@
import { useMovingCellRef } from "./useMovingCellRef";
import { useNanoStore } from "./useNanoStore";
+import { useOnboarding } from "./useOnboarding";
import { usePermissions } from "./usePermissions";
import { useRealtime } from "./useRealtime";
import { useRouteData } from "./useRouteData";
@@ -9,9 +10,10 @@ import { useUser } from "./useUser";
export {
useMovingCellRef,
useNanoStore,
+ useOnboarding,
usePermissions,
useRealtime,
useRouteData,
- useUser,
useUrlParams,
+ useUser,
};
diff --git a/apps/carbon/app/hooks/useOnboarding.tsx b/apps/carbon/app/hooks/useOnboarding.tsx
new file mode 100644
index 0000000000..7b0ee43446
--- /dev/null
+++ b/apps/carbon/app/hooks/useOnboarding.tsx
@@ -0,0 +1,28 @@
+import { useNavigate } from "@remix-run/react";
+import { path } from "~/utils/path";
+import { useRouteData } from "./useRouteData";
+
+export function useOnboarding() {
+ const routeData = useRouteData<{
+ currentIndex: number;
+ onboardingSteps: number;
+ nextPath: string;
+ previousPath: string;
+ }>(path.to.onboarding.root);
+
+ const navigate = useNavigate();
+
+ if (!routeData) {
+ throw new Error("useOnboarding must be used within an onboarding route");
+ }
+
+ return {
+ currentIndex: routeData?.currentIndex,
+ onboardingSteps: routeData?.onboardingSteps,
+ next: routeData?.nextPath,
+ previous: routeData?.previousPath,
+ onPrevious: routeData?.previousPath
+ ? () => navigate(routeData.previousPath)
+ : undefined,
+ };
+}
diff --git a/apps/carbon/app/modules/account/account.models.ts b/apps/carbon/app/modules/account/account.models.ts
index b217f55f07..788981b7ff 100644
--- a/apps/carbon/app/modules/account/account.models.ts
+++ b/apps/carbon/app/modules/account/account.models.ts
@@ -2,6 +2,16 @@ import { withZod } from "@remix-validated-form/with-zod";
import { z } from "zod";
import { zfd } from "zod-form-data";
+export const onboardingUserValidator = withZod(
+ z.object({
+ firstName: z.string().min(1, { message: "First name is required" }),
+ lastName: z.string().min(1, { message: "Last name is required" }),
+ email: z.string().email({ message: "Email is required" }),
+ password: z.string().min(6, { message: "Password is required" }),
+ next: z.string().min(1, { message: "Next is required" }),
+ })
+);
+
export const accountProfileValidator = withZod(
z.object({
firstName: z.string().min(1, { message: "First name is required" }),
diff --git a/apps/carbon/app/modules/account/account.service.ts b/apps/carbon/app/modules/account/account.service.ts
index eec5f744c8..f7cec4b29d 100644
--- a/apps/carbon/app/modules/account/account.service.ts
+++ b/apps/carbon/app/modules/account/account.service.ts
@@ -76,24 +76,15 @@ export async function updateAvatar(
export async function updatePublicAccount(
client: SupabaseClient<Database>,
- args: {
+ account: {
id: string;
+ email?: string;
firstName: string;
lastName: string;
about: string;
}
) {
- const { id, firstName, lastName, about } = args;
- return client
- .from("user")
- .update(
- sanitize({
- firstName,
- lastName,
- about,
- })
- )
- .eq("id", id);
+ return client.from("user").update(sanitize(account)).eq("id", account.id);
}
export async function upsertUserAttributeValue(
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.ts
index 083810541c..f8d30755db 100644
--- a/apps/carbon/app/modules/resources/resources.service.ts
+++ b/apps/carbon/app/modules/resources/resources.service.ts
@@ -827,6 +827,16 @@ export async function insertAttributeCategory(
.single();
}
+export async function insertEmployeeJob(
+ client: SupabaseClient<Database>,
+ job: {
+ id: string;
+ locationId: string;
+ }
+) {
+ return client.from("employeeJob").insert(job).select("id").single();
+}
+
export async function updateAbility(
client: SupabaseClient<Database>,
id: string,
diff --git a/apps/carbon/app/modules/settings/settings.models.ts b/apps/carbon/app/modules/settings/settings.models.ts
index 7162a2bfcc..81a32a76cf 100644
--- a/apps/carbon/app/modules/settings/settings.models.ts
+++ b/apps/carbon/app/modules/settings/settings.models.ts
@@ -2,20 +2,26 @@ import { withZod } from "@remix-validated-form/with-zod";
import { z } from "zod";
import { zfd } from "zod-form-data";
-export const companyValidator = withZod(
+const company = {
+ name: z.string().min(1, { message: "Name is required" }),
+ taxId: zfd.text(z.string().optional()),
+ addressLine1: z.string().min(1, { message: "Address is required" }),
+ addressLine2: zfd.text(z.string().optional()),
+ city: z.string().min(1, { message: "City is required" }),
+ state: z.string().min(1, { message: "State is required" }),
+ postalCode: z.string().min(1, { message: "Zip is required" }),
+ countryCode: zfd.text(z.string().optional()),
+ phone: zfd.text(z.string().optional()),
+ fax: zfd.text(z.string().optional()),
+ email: zfd.text(z.string().optional()),
+ website: zfd.text(z.string().optional()),
+};
+
+export const companyValidator = withZod(z.object(company));
+export const onboardingCompanyValidator = withZod(
z.object({
- name: z.string().min(1, { message: "Name is required" }),
- taxId: zfd.text(z.string().optional()),
- addressLine1: z.string().min(1, { message: "Address is required" }),
- addressLine2: zfd.text(z.string().optional()),
- city: z.string().min(1, { message: "City is required" }),
- state: z.string().min(1, { message: "State is required" }),
- postalCode: z.string().min(1, { message: "Zip is required" }),
- countryCode: zfd.text(z.string().optional()),
- phone: zfd.text(z.string().optional()),
- fax: zfd.text(z.string().optional()),
- email: zfd.text(z.string().optional()),
- website: zfd.text(z.string().optional()),
+ ...company,
+ next: z.string().min(1, { message: "Next is required" }),
})
);
diff --git a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm/CompanyLogoForm.tsx b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm/CompanyLogoForm.tsx
index f87b6feec4..fda2640648 100644
--- a/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm/CompanyLogoForm.tsx
+++ b/apps/carbon/app/modules/settings/ui/Company/CompanyLogoForm/CompanyLogoForm.tsx
@@ -22,7 +22,7 @@ const CompanyLogoForm = ({ company }: CompanyLogoFormProps) => {
const fileExtension = logo.name.substring(logo.name.lastIndexOf(".") + 1);
const imageUpload = await supabase.storage
- .from("avatars")
+ .from("public")
.upload(`logo.${fileExtension}`, logo, {
cacheControl: `${12 * 60 * 60}`,
upsert: true,
diff --git a/apps/carbon/app/routes/onboarding+/_layout.tsx b/apps/carbon/app/routes/onboarding+/_layout.tsx
new file mode 100644
index 0000000000..11c05754f9
--- /dev/null
+++ b/apps/carbon/app/routes/onboarding+/_layout.tsx
@@ -0,0 +1,114 @@
+import { useColor } from "@carbon/react";
+import {
+ Avatar,
+ Box,
+ Grid,
+ GridItem,
+ HStack,
+ IconButton,
+} from "@chakra-ui/react";
+import { redirect, type LoaderFunctionArgs } from "@remix-run/node";
+import { Outlet } from "@remix-run/react";
+import { BsFillHexagonFill } from "react-icons/bs";
+import { getLocationsList } from "~/modules/resources";
+import { getCompany } from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { onboardingList, path } from "~/utils/path";
+
+import type { ShouldRevalidateFunction } from "@remix-run/react";
+
+export const shouldRevalidate: ShouldRevalidateFunction = () => true;
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ create: "settings",
+ });
+
+ const [company, locations] = await Promise.all([
+ getCompany(client),
+ getLocationsList(client),
+ ]);
+ // we don't need to do onboarding if we have a company name or locations
+ if (company.data?.name && locations.data?.length) {
+ return redirect(path.to.authenticatedRoot);
+ }
+
+ const pathname = new URL(request.url).pathname;
+ const pathIndex = onboardingList.findIndex((p) => p === pathname);
+
+ const previousPath =
+ pathIndex === 0 ? undefined : onboardingList[pathIndex - 1];
+
+ const nextPath =
+ pathIndex === onboardingList.length - 1
+ ? path.to.authenticatedRoot
+ : onboardingList[pathIndex + 1];
+
+ return {
+ currentIndex: pathIndex,
+ onboardingSteps: onboardingList.length,
+ previousPath,
+ nextPath,
+ };
+}
+
+export default function OnboardingLayout() {
+ // const { currentIndex, onboardingSteps } = useOnboarding();
+
+ return (
+ <Grid h="100vh" w="100vw" templateColumns="auto 1fr">
+ <SidebarPlaceholder />
+ <Grid templateRows="auto 1fr" h="full" w="full">
+ <TopbarPlaceholder />
+ <div>
+ <Outlet />
+ </div>
+ </Grid>
+ </Grid>
+ );
+}
+
+function TopbarPlaceholder() {
+ return (
+ <GridItem
+ bg={useColor("white")}
+ borderBottom={1}
+ borderBottomColor={useColor("gray.200")}
+ borderBottomStyle="solid"
+ display="grid"
+ gap={4}
+ gridTemplateColumns="1fr"
+ position="sticky"
+ px={4}
+ top={0}
+ zIndex={1}
+ >
+ <HStack py={2} justifyContent="end" spacing={1}>
+ <Avatar size="sm" />
+ </HStack>
+ </GridItem>
+ );
+}
+
+function SidebarPlaceholder() {
+ return (
+ <Box
+ h="full"
+ borderRight={1}
+ borderRightColor={useColor("gray.200")}
+ borderRightStyle="solid"
+ background={useColor("white")}
+ zIndex={1}
+ >
+ <IconButton
+ aria-label="Home"
+ variant="ghost"
+ size="lg"
+ icon={<BsFillHexagonFill />}
+ position="sticky"
+ top={0}
+ mb={4}
+ />
+ </Box>
+ );
+}
diff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsx
new file mode 100644
index 0000000000..ba0ca31691
--- /dev/null
+++ b/apps/carbon/app/routes/onboarding+/company.tsx
@@ -0,0 +1,170 @@
+import {
+ Button,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ VStack,
+} from "@chakra-ui/react";
+import { getLocalTimeZone } from "@internationalized/date";
+import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { ValidatedForm, validationError } from "remix-validated-form";
+import { Hidden, Input, Submit } from "~/components/Form";
+import { useOnboarding } from "~/hooks";
+import {
+ getLocationsList,
+ insertEmployeeJob,
+ upsertLocation,
+} from "~/modules/resources";
+import {
+ getCompany,
+ insertCompany,
+ onboardingCompanyValidator,
+ updateCompany,
+} from "~/modules/settings";
+import { requirePermissions } from "~/services/auth";
+import { assertIsPost } from "~/utils/http";
+
+export async function loader({ request }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ update: "settings",
+ });
+
+ const company = await getCompany(client);
+ if (company.error || !company.data) {
+ return json({
+ company: null,
+ });
+ }
+
+ return { company: company.data };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "settings",
+ });
+
+ const validation = await onboardingCompanyValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { next, ...data } = validation.data;
+
+ const [company, locations] = await Promise.all([
+ getCompany(client),
+ getLocationsList(client),
+ ]);
+
+ const location = locations?.data?.[0];
+
+ if (company.data && location) {
+ const [companyUpdate, locationUpdate] = await Promise.all([
+ updateCompany(client, { ...data, updatedBy: userId }),
+ upsertLocation(client, {
+ ...location,
+ ...data,
+ timezone: getLocalTimeZone(),
+ updatedBy: userId,
+ }),
+ ]);
+ if (companyUpdate.error) {
+ console.error(companyUpdate.error);
+ throw new Error("Fatal: failed to update company");
+ }
+ if (locationUpdate.error) {
+ console.error(locationUpdate.error);
+ throw new Error("Fatal: failed to update location");
+ }
+ } else {
+ const [companyInsert, locationInsert] = await Promise.all([
+ insertCompany(client, data),
+ upsertLocation(client, {
+ ...data,
+ name: "Headquarters",
+ timezone: getLocalTimeZone(),
+ createdBy: userId,
+ }),
+ ]);
+ if (companyInsert.error) {
+ console.error(companyInsert.error);
+ throw new Error("Fatal: failed to insert company");
+ }
+ if (locationInsert.error) {
+ console.error(locationInsert.error);
+ throw new Error("Fatal: failed to insert location");
+ }
+
+ const locationId = locationInsert.data?.id;
+ if (!locationId) {
+ throw new Error("Fatal: failed to get location ID");
+ }
+
+ await insertEmployeeJob(client, {
+ id: userId,
+ locationId,
+ });
+ }
+
+ return redirect(next);
+}
+
+export default function OnboardingUser() {
+ const { company } = useLoaderData<typeof loader>();
+ const { next, previous, onPrevious } = useOnboarding();
+
+ const initialValues = {
+ name: company?.name ?? "",
+ addressLine1: company?.addressLine1 ?? "",
+ city: company?.city ?? "",
+ state: company?.state ?? "",
+ postalCode: company?.postalCode ?? "",
+ };
+
+ return (
+ <Modal size="lg" isOpen onClose={() => 0}>
+ <ModalOverlay />
+ <ModalContent>
+ <ValidatedForm
+ autoComplete="off"
+ validator={onboardingCompanyValidator}
+ defaultValues={initialValues}
+ method="post"
+ >
+ <ModalHeader>Now let's setup your company</ModalHeader>
+
+ <ModalBody>
+ <Hidden name="next" value={next} />
+ <VStack w="full" spacing={4}>
+ <Input name="name" label="Company Name" />
+ <Input name="addressLine1" label="Address" />
+ <Input name="city" label="City" />
+ <Input name="state" label="State" />
+ <Input name="postalCode" label="Zip Code" />
+ </VStack>
+ </ModalBody>
+
+ <ModalFooter justifyContent="space-between">
+ <Button
+ isDisabled={!previous}
+ size="md"
+ disabled
+ onClick={onPrevious}
+ >
+ Previous
+ </Button>
+ <Submit>Next</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/carbon/app/routes/onboarding+/index.tsx b/apps/carbon/app/routes/onboarding+/index.tsx
new file mode 100644
index 0000000000..6296ab71fe
--- /dev/null
+++ b/apps/carbon/app/routes/onboarding+/index.tsx
@@ -0,0 +1,6 @@
+import { redirect } from "@remix-run/node";
+import { onboardingList } from "~/utils/path";
+
+export async function loader() {
+ return redirect(onboardingList[0]);
+}
diff --git a/apps/carbon/app/routes/onboarding+/location.tsx b/apps/carbon/app/routes/onboarding+/location.tsx
new file mode 100644
index 0000000000..46015915cc
--- /dev/null
+++ b/apps/carbon/app/routes/onboarding+/location.tsx
@@ -0,0 +1,3 @@
+export default function OnboardingLocation() {
+ return null;
+}
diff --git a/apps/carbon/app/routes/onboarding+/user.tsx b/apps/carbon/app/routes/onboarding+/user.tsx
new file mode 100644
index 0000000000..3494746ecf
--- /dev/null
+++ b/apps/carbon/app/routes/onboarding+/user.tsx
@@ -0,0 +1,139 @@
+import {
+ Button,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalOverlay,
+ VStack,
+} from "@chakra-ui/react";
+import { redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { ValidatedForm, validationError } from "remix-validated-form";
+import { Hidden, Input, Password, Submit } from "~/components/Form";
+import { useOnboarding } from "~/hooks";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import {
+ onboardingUserValidator,
+ updatePublicAccount,
+} from "~/modules/account";
+import { getUser } from "~/modules/users/users.server";
+import { requirePermissions } from "~/services/auth";
+import { destroyAuthSession } from "~/services/session";
+import type { TypeOfValidator } from "~/types/validators";
+import { assertIsPost } from "~/utils/http";
+
+export async function loader({ request }: ActionFunctionArgs) {
+ const { client, userId } = await requirePermissions(request, {
+ update: "users",
+ });
+
+ const user = await getUser(client, userId);
+ if (user.error || !user.data) {
+ await destroyAuthSession(request);
+ }
+
+ return { user: user.data };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "users",
+ });
+
+ const validation = await onboardingUserValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { firstName, lastName, email, password, next } = validation.data;
+
+ const updatePassword =
+ await getSupabaseServiceRole().auth.admin.updateUserById(userId, {
+ email,
+ password,
+ });
+
+ if (updatePassword.error) {
+ console.error(updatePassword.error);
+ throw new Error("Fatal: failed to update password");
+ }
+
+ const updateAccount = await updatePublicAccount(client, {
+ id: userId,
+ email,
+ firstName,
+ lastName,
+ about: "",
+ });
+
+ if (updateAccount.error) {
+ console.error(updateAccount.error);
+ throw new Error("Fatal: failed to update account");
+ }
+
+ return redirect(next);
+}
+
+export default function OnboardingUser() {
+ const { user } = useLoaderData<typeof loader>();
+ const { next, previous, onPrevious } = useOnboarding();
+
+ const initialValues = {} as TypeOfValidator<typeof onboardingUserValidator>;
+
+ if (user?.email && user.email !== "[email protected]") {
+ initialValues.email = user.email;
+ }
+ if (
+ user?.firstName &&
+ user?.lastName &&
+ user?.firstName !== "Carbon" &&
+ user?.lastName !== "Admin"
+ ) {
+ initialValues.firstName = user?.firstName!;
+ initialValues.lastName = user?.lastName!;
+ }
+
+ return (
+ <Modal size="lg" isOpen onClose={() => 0}>
+ <ModalOverlay />
+ <ModalContent>
+ <ValidatedForm
+ autoComplete="off"
+ validator={onboardingUserValidator}
+ defaultValues={initialValues}
+ method="post"
+ >
+ <ModalHeader>Welcome! First let's setup your account</ModalHeader>
+
+ <ModalBody>
+ <Hidden name="next" value={next} />
+ <VStack w="full" spacing={4}>
+ <Input name="firstName" label="First Name" />
+ <Input name="lastName" label="Last Name" />
+ <Input autoComplete="off" name="email" label="Email" />
+ <Password autoComplete="off" name="password" label="Password" />
+ </VStack>
+ </ModalBody>
+
+ <ModalFooter justifyContent="space-between">
+ <Button
+ isDisabled={!previous}
+ size="md"
+ disabled
+ onClick={onPrevious}
+ >
+ Previous
+ </Button>
+ <Submit>Next</Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index 6169b80863..e4f3b74d58 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -2,12 +2,13 @@ import { useColor, useNotification } from "@carbon/react";
import { Flex, Grid, GridItem, VStack } from "@chakra-ui/react";
import { SkipNavContent } from "@chakra-ui/skip-nav";
import type { LoaderFunctionArgs } from "@remix-run/node";
-import { json } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData, useNavigation } from "@remix-run/react";
import NProgress from "nprogress";
import { useEffect } from "react";
import { IconSidebar, Topbar } from "~/components/Layout";
import { SupabaseProvider, getSupabase } from "~/lib/supabase";
+import { getCompany } from "~/modules/settings";
import { RealtimeDataProvider } from "~/modules/shared";
import {
getUser,
@@ -20,6 +21,7 @@ import {
getSessionFlash,
requireAuthSession,
} from "~/services/session";
+import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
const { accessToken, expiresAt, expiresIn, userId } =
@@ -29,18 +31,25 @@ export async function loader({ request }: LoaderFunctionArgs) {
const client = getSupabase(accessToken);
// parallelize the requests
- const [sessionFlash, user, claims, groups, defaults] = await Promise.all([
- getSessionFlash(request),
- getUser(client, userId),
- getUserClaims(request),
- getUserGroups(client, userId),
- getUserDefaults(client, userId),
- ]);
+ const [sessionFlash, company, user, claims, groups, defaults] =
+ await Promise.all([
+ getSessionFlash(request),
+ getCompany(client),
+ getUser(client, userId),
+ getUserClaims(request),
+ getUserGroups(client, userId),
+ getUserDefaults(client, userId),
+ ]);
if (!claims || user.error || !user.data || !groups.data) {
await destroyAuthSession(request);
}
+ const requiresOnboarding = !company.data?.name;
+ if (requiresOnboarding) {
+ return redirect(path.to.onboarding.root);
+ }
+
return json(
{
session: {
@@ -48,7 +57,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
expiresIn,
expiresAt,
},
-
+ company: company.data,
user: user.data,
groups: groups.data,
defaults: defaults.data,
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 13253ac286..6a51fbdf14 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -3,6 +3,7 @@ import { generatePath } from "@remix-run/react";
const x = "/x"; // from ~/routes/x+ folder
const api = "/api"; // from ~/routes/api+ folder
const file = "/file"; // from ~/routes/file+ folder
+const onboarding = "/onboarding"; // from ~/routes/onboarding+ folder
export const path = {
to: {
@@ -44,6 +45,12 @@ export const path = {
purchaseOrder: (id: string) =>
generatePath(`${file}/purchase-order/${id}`),
},
+ onboarding: {
+ company: `${onboarding}/company`,
+ location: `${onboarding}/location`,
+ root: `${onboarding}`,
+ user: `${onboarding}/user`,
+ },
authenticatedRoot: x,
abilities: `${x}/resources/abilities`,
ability: (id: string) => generatePath(`${x}/resources/ability/${id}`),
@@ -390,3 +397,8 @@ export const path = {
generatePath(`/${x}/resources/work-cells/list/${id}`),
},
} as const;
+
+export const onboardingList = [
+ path.to.onboarding.user,
+ path.to.onboarding.company,
+] as const;
diff --git a/packages/database/SCHEMA.md b/packages/database/SCHEMA.md
index e38d393681..439bac0b6e 100644
--- a/packages/database/SCHEMA.md
+++ b/packages/database/SCHEMA.md
@@ -410,6 +410,33 @@ VALUES
('avatars', 'avatars', true),
('private', 'private', false);
+CREATE POLICY "Anyone can read public buckets"
+ON storage.objects FOR SELECT USING (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+);
+
+CREATE POLICY "Employees with settings_create can insert into the public bucket"
+ON storage.objects FOR INSERT WITH CHECK (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('settings_create')::boolean,false)
+);
+
+CREATE POLICY "Employees with settings_update can update the public bucket"
+ON storage.objects FOR UPDATE USING (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('settings_update')::boolean,false)
+);
+
+CREATE POLICY "Employees with settings_delete can delete from public bucket"
+ON storage.objects FOR DELETE USING (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('settings_delete')::boolean,false)
+);
+
CREATE POLICY "Anyone can view avatars"
ON storage.objects FOR SELECT USING (
bucket_id = 'avatars'
@@ -7235,11 +7262,13 @@ CREATE TABLE "company" (
"fax" TEXT,
"email" TEXT,
"website" TEXT,
+ "updatedBy" TEXT,
CONSTRAINT "company_pkey" PRIMARY KEY ("id"),
-- this is a hack to make sure that this table only ever has one row
CONSTRAINT "accountDefault_id_check" CHECK ("id" = TRUE),
- CONSTRAINT "accountDefault_id_unique" UNIQUE ("id")
+ CONSTRAINT "accountDefault_id_unique" UNIQUE ("id"),
+ CONSTRAINT "accountDefault_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
ALTER TABLE "company" ENABLE ROW LEVEL SECURITY;
@@ -7250,6 +7279,13 @@ CREATE POLICY "Authenticated users can view company" ON "company"
auth.role() = 'authenticated'
);
+CREATE POLICY "Employees with settings_create can create company" ON "company"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('settings_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
CREATE POLICY "Employees with settings_update can update company" ON "company"
FOR UPDATE
USING (
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index e02909cede..55c5ddfd64 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1088,6 +1088,7 @@ export interface Database {
postalCode: string | null;
state: string | null;
taxId: string | null;
+ updatedBy: string | null;
website: string | null;
};
Insert: {
@@ -1104,6 +1105,7 @@ export interface Database {
postalCode?: string | null;
state?: string | null;
taxId?: string | null;
+ updatedBy?: string | null;
website?: string | null;
};
Update: {
@@ -1120,9 +1122,23 @@ export interface Database {
postalCode?: string | null;
state?: string | null;
taxId?: string | null;
+ updatedBy?: string | null;
website?: string | null;
};
- Relationships: [];
+ Relationships: [
+ {
+ foreignKeyName: "accountDefault_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "user";
+ referencedColumns: ["id"];
+ },
+ {
+ foreignKeyName: "accountDefault_updatedBy_fkey";
+ columns: ["updatedBy"];
+ referencedRelation: "userDefaults";
+ referencedColumns: ["userId"];
+ }
+ ];
};
contact: {
Row: {
diff --git a/packages/database/supabase/migrations/20230123004514_buckets.sql b/packages/database/supabase/migrations/20230123004514_buckets.sql
index 5763135e46..ed5ae5ac4b 100644
--- a/packages/database/supabase/migrations/20230123004514_buckets.sql
+++ b/packages/database/supabase/migrations/20230123004514_buckets.sql
@@ -4,6 +4,33 @@ VALUES
('avatars', 'avatars', true),
('private', 'private', false);
+CREATE POLICY "Anyone can read public buckets"
+ON storage.objects FOR SELECT USING (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+);
+
+CREATE POLICY "Employees with settings_create can insert into the public bucket"
+ON storage.objects FOR INSERT WITH CHECK (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('settings_create')::boolean,false)
+);
+
+CREATE POLICY "Employees with settings_update can update the public bucket"
+ON storage.objects FOR UPDATE USING (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('settings_update')::boolean,false)
+);
+
+CREATE POLICY "Employees with settings_delete can delete from public bucket"
+ON storage.objects FOR DELETE USING (
+ bucket_id = 'public'
+ AND (auth.role() = 'authenticated')
+ AND coalesce(get_my_claim('settings_delete')::boolean,false)
+);
+
CREATE POLICY "Anyone can view avatars"
ON storage.objects FOR SELECT USING (
bucket_id = 'avatars'
diff --git a/packages/database/supabase/migrations/20231219110852_company.sql b/packages/database/supabase/migrations/20231219110852_company.sql
index ad22b79339..64b761fca7 100644
--- a/packages/database/supabase/migrations/20231219110852_company.sql
+++ b/packages/database/supabase/migrations/20231219110852_company.sql
@@ -19,7 +19,7 @@ CREATE TABLE "company" (
-- this is a hack to make sure that this table only ever has one row
CONSTRAINT "accountDefault_id_check" CHECK ("id" = TRUE),
CONSTRAINT "accountDefault_id_unique" UNIQUE ("id"),
- CONSTRAINT "accountDefault_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id"),
+ CONSTRAINT "accountDefault_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id")
);
ALTER TABLE "company" ENABLE ROW LEVEL SECURITY;
@@ -30,6 +30,13 @@ CREATE POLICY "Authenticated users can view company" ON "company"
auth.role() = 'authenticated'
);
+CREATE POLICY "Employees with settings_create can create company" ON "company"
+ FOR INSERT
+ WITH CHECK (
+ coalesce(get_my_claim('settings_create')::boolean, false) = true
+ AND (get_my_claim('role'::text)) = '"employee"'::jsonb
+ );
+
CREATE POLICY "Employees with settings_update can update company" ON "company"
FOR UPDATE
USING (