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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
⚡storage + my account + avatars (#4)
Brad Barbinde72b13d4de2
diff --git a/apps/carbon/app/components/Avatar/Avatar.tsx b/apps/carbon/app/components/Avatar/Avatar.tsxnew file mode 100644index 0000000000..affe14d067--- /dev/null+++ b/apps/carbon/app/components/Avatar/Avatar.tsx@@ -0,0 +1,18 @@+import { Avatar as ChakraAvatar, forwardRef } from "@chakra-ui/react";+import { SUPABASE_API_URL } from "~/config/env";+import type { AvatarProps as ChakraAvatarProps } from "@chakra-ui/react";++type AvatarProps = ChakraAvatarProps & {+ path: string | null;+ bucket?: string;+};++export const Avatar = forwardRef(+ ({ path, bucket = "avatars", ...props }: AvatarProps, ref) => {+ const imagePath = path+ ? `${SUPABASE_API_URL}/storage/v1/object/public/${bucket}/${path}`+ : undefined;++ return <ChakraAvatar ref={ref} src={imagePath} {...props} />;+ }+);diff --git a/apps/carbon/app/components/Avatar/index.ts b/apps/carbon/app/components/Avatar/index.tsnew file mode 100644index 0000000000..fe46201a20--- /dev/null+++ b/apps/carbon/app/components/Avatar/index.ts@@ -0,0 +1,3 @@+import { Avatar } from "./Avatar";++export { Avatar };diff --git a/apps/carbon/app/components/Form/Hidden.tsx b/apps/carbon/app/components/Form/Hidden.tsxindex 613c6c6b65..573fdd1700 100644--- a/apps/carbon/app/components/Form/Hidden.tsx+++ b/apps/carbon/app/components/Form/Hidden.tsx@@ -9,10 +9,11 @@ import { useField } from "remix-validated-form";type FormHiddenProps = InputProps & {name: string;+ value?: string;};const Hidden = forwardRef<HTMLInputElement, FormHiddenProps>(- ({ name, ...rest }, ref) => {+ ({ name, value, ...rest }, ref) => {const { getInputProps, error } = useField(name);return (@@ -23,6 +24,7 @@ const Hidden = forwardRef<HTMLInputElement, FormHiddenProps>(id: name,...rest,})}+ value={value}type="hidden"/>{error && <FormErrorMessage>{error}</FormErrorMessage>}diff --git a/apps/carbon/app/components/Form/Password.tsx b/apps/carbon/app/components/Form/Password.tsxindex 3a6899a3f8..ac4273a748 100644--- a/apps/carbon/app/components/Form/Password.tsx+++ b/apps/carbon/app/components/Form/Password.tsx@@ -8,48 +8,48 @@ import {InputGroup,InputRightElement,} from "@chakra-ui/react";-import { useState } from "react";+import { forwardRef, useState } from "react";import { useField } from "remix-validated-form";-type FormPasswordProps = {+type FormPasswordProps = InputProps & {name: string;label?: string;isRequired?: boolean;};-const Password = ({- name,- label,- isRequired,- ...rest-}: FormPasswordProps & InputProps) => {- const { getInputProps, error } = useField(name);- const [passwordVisible, setPasswordVisible] = useState(false);+const Password = forwardRef<HTMLInputElement, FormPasswordProps>(+ ({ name, label, isRequired, ...rest }, ref) => {+ const { getInputProps, error } = useField(name);+ const [passwordVisible, setPasswordVisible] = useState(false);- return (- <FormControl isInvalid={!!error} isRequired={isRequired}>- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}- <InputGroup size="md">- <Input- {...getInputProps({- id: name,- ...rest,- })}- type={passwordVisible ? "text" : "password"}- />- <InputRightElement width="4.5rem">- <Button- h="1.75rem"- size="sm"- onClick={() => setPasswordVisible(!passwordVisible)}- >- {passwordVisible ? "Hide" : "Show"}- </Button>- </InputRightElement>- </InputGroup>- {error && <FormErrorMessage>{error}</FormErrorMessage>}- </FormControl>- );-};+ return (+ <FormControl isInvalid={!!error} isRequired={isRequired}>+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}+ <InputGroup size="md">+ <Input+ {...getInputProps({+ id: name,+ ...rest,+ })}+ ref={ref}+ type={passwordVisible ? "text" : "password"}+ />+ <InputRightElement width="4.5rem">+ <Button+ h="1.75rem"+ size="sm"+ onClick={() => setPasswordVisible(!passwordVisible)}+ >+ {passwordVisible ? "Hide" : "Show"}+ </Button>+ </InputRightElement>+ </InputGroup>+ {error && <FormErrorMessage>{error}</FormErrorMessage>}+ </FormControl>+ );+ }+);++Password.displayName = "Password";export default Password;diff --git a/apps/carbon/app/components/Form/Submit.tsx b/apps/carbon/app/components/Form/Submit.tsxindex 676d5a7f93..6d17cac686 100644--- a/apps/carbon/app/components/Form/Submit.tsx+++ b/apps/carbon/app/components/Form/Submit.tsx@@ -13,8 +13,8 @@ export const Submit = ({type="submit"size="md"colorScheme="brand"- isLoading={isSubmitting}- disabled={isSubmitting}+ isLoading={isSubmitting || props.isLoading}+ disabled={isSubmitting || props.disabled}{...props}>{children}diff --git a/apps/carbon/app/components/Form/Textarea.tsx b/apps/carbon/app/components/Form/Textarea.tsxnew file mode 100644index 0000000000..a95f7a166b--- /dev/null+++ b/apps/carbon/app/components/Form/Textarea.tsx@@ -0,0 +1,56 @@+import type { TextareaProps } from "@chakra-ui/react";+import {+ FormControl,+ FormErrorMessage,+ FormLabel,+ Text,+ Textarea as ChakraTextArea,+} from "@chakra-ui/react";+import type { ChangeEvent } from "react";+import { forwardRef, useState } from "react";+import { useField } from "remix-validated-form";++type FormTextArea = TextareaProps & {+ name: string;+ label?: string;+ characterLimit?: number;+ isRequired?: boolean;+};++const TextArea = forwardRef<HTMLTextAreaElement, FormTextArea>(+ ({ name, label, characterLimit, isRequired, ...rest }, ref) => {+ const { getInputProps, error, defaultValue } = useField(name);+ const [characterCount, setCharacterCount] = useState(+ defaultValue?.length ?? 0+ );++ const onChange = (e: ChangeEvent<HTMLTextAreaElement>) => {+ if (characterLimit) setCharacterCount(e.target.value.length);+ };++ return (+ <FormControl isInvalid={!!error} isRequired={isRequired}>+ {label && <FormLabel htmlFor={name}>{label}</FormLabel>}+ <ChakraTextArea+ ref={ref}+ {...getInputProps({+ id: name,+ ...rest,+ })}+ maxLength={characterLimit}+ onChange={onChange}+ />+ {characterLimit && (+ <Text fontSize="sm" color="gray.500">+ {characterCount} of {characterLimit}+ </Text>+ )}+ {error && <FormErrorMessage>{error}</FormErrorMessage>}+ </FormControl>+ );+ }+);++TextArea.displayName = "TextArea";++export default TextArea;diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.tsindex 744f58e282..2e6a386534 100644--- a/apps/carbon/app/components/Form/index.ts+++ b/apps/carbon/app/components/Form/index.ts@@ -5,6 +5,17 @@ import Password from "./Password";import Radios from "./Radios";import Select from "./Select";import Submit from "./Submit";+import TextArea from "./Textarea";import Users from "./Users";-export { Color, Input, Hidden, Password, Radios, Select, Submit, Users };+export {+ Color,+ Input,+ Hidden,+ Password,+ Radios,+ Select,+ Submit,+ TextArea,+ Users,+};diff --git a/apps/carbon/app/components/Layout/PageTitle/PageTitle.tsx b/apps/carbon/app/components/Layout/PageTitle/PageTitle.tsxnew file mode 100644index 0000000000..62984faef5--- /dev/null+++ b/apps/carbon/app/components/Layout/PageTitle/PageTitle.tsx@@ -0,0 +1,21 @@+import { Heading, Text, VStack } from "@chakra-ui/react";++type PageTitleProps = {+ title: string;+ subtitle?: string;+};++const PageTitle = ({ title, subtitle }: PageTitleProps) => {+ return (+ <VStack spacing={2} alignItems="start" w="full" mb={4}>+ <Heading size="lg">{title}</Heading>+ {subtitle && (+ <Text fontSize={14} color="gray.500">+ {subtitle}+ </Text>+ )}+ </VStack>+ );+};++export default PageTitle;diff --git a/apps/carbon/app/components/Layout/PageTitle/index.ts b/apps/carbon/app/components/Layout/PageTitle/index.tsnew file mode 100644index 0000000000..ce9b043a16--- /dev/null+++ b/apps/carbon/app/components/Layout/PageTitle/index.ts@@ -0,0 +1,3 @@+import PageTitle from "./PageTitle";++export default PageTitle;diff --git a/apps/carbon/app/components/Navigation/Sidebar/ContentSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsxsimilarity index 100%rename from apps/carbon/app/components/Navigation/Sidebar/ContentSidebar.tsxrename to apps/carbon/app/components/Layout/Sidebar/ContentSidebar.tsxdiff --git a/apps/carbon/app/components/Navigation/Sidebar/IconSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsxsimilarity index 100%rename from apps/carbon/app/components/Navigation/Sidebar/IconSidebar.tsxrename to apps/carbon/app/components/Layout/Sidebar/IconSidebar.tsxdiff --git a/apps/carbon/app/components/Navigation/Sidebar/MultiTabSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/MultiTabSidebar.tsxsimilarity index 100%rename from apps/carbon/app/components/Navigation/Sidebar/MultiTabSidebar.tsxrename to apps/carbon/app/components/Layout/Sidebar/MultiTabSidebar.tsxdiff --git a/apps/carbon/app/components/Navigation/Sidebar/index.ts b/apps/carbon/app/components/Layout/Sidebar/index.tssimilarity index 100%rename from apps/carbon/app/components/Navigation/Sidebar/index.tsrename to apps/carbon/app/components/Layout/Sidebar/index.tsdiff --git a/apps/carbon/app/components/Navigation/Sidebar/useSidebar.tsx b/apps/carbon/app/components/Layout/Sidebar/useSidebar.tsxsimilarity index 100%rename from apps/carbon/app/components/Navigation/Sidebar/useSidebar.tsxrename to apps/carbon/app/components/Layout/Sidebar/useSidebar.tsxdiff --git a/apps/carbon/app/components/Navigation/Topbar/AvatarMenu.tsx b/apps/carbon/app/components/Layout/Topbar/AvatarMenu.tsxsimilarity index 85%rename from apps/carbon/app/components/Navigation/Topbar/AvatarMenu.tsxrename to apps/carbon/app/components/Layout/Topbar/AvatarMenu.tsxindex 6fb812a3a0..04ffbe143a 100644--- a/apps/carbon/app/components/Navigation/Topbar/AvatarMenu.tsx+++ b/apps/carbon/app/components/Layout/Topbar/AvatarMenu.tsx@@ -1,11 +1,11 @@import {- Avatar,Menu,MenuButton,MenuDivider,MenuItem,MenuList,} from "@chakra-ui/react";+import { Avatar } from "~/components/Avatar";import { Form, Link } from "@remix-run/react";import { BiLogOut } from "react-icons/bi";import { CgProfile } from "react-icons/cg";@@ -18,6 +18,7 @@ const AvatarMenu = () => {<Menu><MenuButtonas={Avatar}+ path={user.avatarUrl}role="button"name=""size="sm"@@ -26,7 +27,7 @@ const AvatarMenu = () => {<MenuList fontSize="sm" boxShadow="xl" minW={48}><MenuItem>Signed in as {`${user.firstName} ${user.lastName}`}</MenuItem><MenuDivider />- <MenuItem as={Link} to="/account" icon={<CgProfile />}>+ <MenuItem as={Link} to="/app/account/profile" icon={<CgProfile />}>My Profile</MenuItem><Form method="post" action="/logout">diff --git a/apps/carbon/app/components/Navigation/Topbar/Breadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsxsimilarity index 100%rename from apps/carbon/app/components/Navigation/Topbar/Breadcrumbs.tsxrename to apps/carbon/app/components/Layout/Topbar/Breadcrumbs.tsxdiff --git a/apps/carbon/app/components/Navigation/Topbar/Logo.tsx b/apps/carbon/app/components/Layout/Topbar/Logo.tsxsimilarity index 100%rename from apps/carbon/app/components/Navigation/Topbar/Logo.tsxrename to apps/carbon/app/components/Layout/Topbar/Logo.tsxdiff --git a/apps/carbon/app/components/Navigation/Topbar/Topbar.tsx b/apps/carbon/app/components/Layout/Topbar/Topbar.tsxsimilarity index 100%rename from apps/carbon/app/components/Navigation/Topbar/Topbar.tsxrename to apps/carbon/app/components/Layout/Topbar/Topbar.tsxdiff --git a/apps/carbon/app/components/Navigation/Topbar/index.ts b/apps/carbon/app/components/Layout/Topbar/index.tssimilarity index 100%rename from apps/carbon/app/components/Navigation/Topbar/index.tsrename to apps/carbon/app/components/Layout/Topbar/index.tsdiff --git a/apps/carbon/app/components/Navigation/Topbar/useBreadcrumbs.tsx b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsxsimilarity index 64%rename from apps/carbon/app/components/Navigation/Topbar/useBreadcrumbs.tsxrename to apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsxindex 8fea10e1b1..ed07ea6010 100644--- a/apps/carbon/app/components/Navigation/Topbar/useBreadcrumbs.tsx+++ b/apps/carbon/app/components/Layout/Topbar/useBreadcrumbs.tsx@@ -9,6 +9,41 @@ export default function useBreadcrumbs(): Route[] {switch (match.id) {case "root":return acc.concat({ to: "/app", name: "Home", icon: <IoHomeSharp /> });+ case "routes/app.account":+ return acc.concat({+ name: "Account",+ to: match.pathname,+ });+ case "routes/app.account.profile":+ return acc.concat({+ name: "Profile",+ to: match.pathname,+ });+ case "routes/app.account.personal":+ return acc.concat({+ name: "Personal",+ to: match.pathname,+ });+ case "routes/app.account.password":+ return acc.concat({+ name: "Password",+ to: match.pathname,+ });+ case "routes/app.account.notifications":+ return acc.concat({+ name: "Notifications",+ to: match.pathname,+ });+ case "routes/app.account.security":+ return acc.concat({+ name: "Security",+ to: match.pathname,+ });+ case "routes/app.account.settings":+ return acc.concat({+ name: "Settings",+ to: match.pathname,+ });case "routes/app.parts":return acc.concat({name: "Parts",diff --git a/apps/carbon/app/components/Layout/index.ts b/apps/carbon/app/components/Layout/index.tsnew file mode 100644index 0000000000..447c41c1e2--- /dev/null+++ b/apps/carbon/app/components/Layout/index.ts@@ -0,0 +1,5 @@+import { IconSidebar, ContentSidebar } from "./Sidebar";+import PageTitle from "./PageTitle";+import Topbar from "./Topbar";++export { ContentSidebar, IconSidebar, PageTitle, Topbar };diff --git a/apps/carbon/app/components/Navigation/index.ts b/apps/carbon/app/components/Navigation/index.tsdeleted file mode 100644index c911882b67..0000000000--- a/apps/carbon/app/components/Navigation/index.ts+++ /dev/null@@ -1,4 +0,0 @@-import Topbar from "./Topbar";-import { IconSidebar, ContentSidebar } from "./Sidebar";--export { ContentSidebar, IconSidebar, Topbar };diff --git a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsxindex 5d57aac3ae..98e27c27d2 100644--- a/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx+++ b/apps/carbon/app/components/Selectors/UserSelect/components/SelectionList.tsx@@ -1,6 +1,5 @@import { useColor } from "@carbon/react";import {- Avatar,Box,Checkbox,Flex,@@ -12,6 +11,7 @@ import {} from "@chakra-ui/react";import { useMemo } from "react";import { MdPlaylistAdd, MdOutlineClear } from "react-icons/md";+import { Avatar } from "~/components/Avatar";import useUserSelectContext from "../provider";import { isGroup } from "../useUserSelect";@@ -72,7 +72,16 @@ const SelectionList = () => {</>) : (<>- <Avatar size="sm" />+ {"fullName" in item ? (+ <Avatar+ name={item.fullName ?? undefined}+ path={item.avatarUrl}+ size="sm"+ />+ ) : (+ <Avatar name={item.name} path={null} size="sm" />+ )}+<Box display="flex" alignItems="center" flexGrow={2}><Text fontSize={14} noOfLines={1}>{item.label}diff --git a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.tsindex b1c54098da..0f43f43bcb 100644--- a/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts+++ b/apps/carbon/app/components/Selectors/UserSelect/useUserSelect.ts@@ -456,7 +456,6 @@ export default function useUserSelect(props: UserSelectProps) {if (innerProps.isMulti && !innerProps.resetAfterSelection) {setFocusedId(selectionItem.uid!);} else {- console.log("resetting");commit();clear();}diff --git a/apps/carbon/app/entry.client.tsx b/apps/carbon/app/entry.client.tsxindex ddc50ba306..b908c8b20e 100644--- a/apps/carbon/app/entry.client.tsx+++ b/apps/carbon/app/entry.client.tsx@@ -29,3 +29,10 @@ hydrateRoot(<RemixBrowser /></ClientCacheProvider>);++if ("serviceWorker" in navigator) {+ window.addEventListener("load", () => {+ // we will register it after the page complete the load+ navigator.serviceWorker.register("/serviceWorker.js");+ });+}diff --git a/apps/carbon/app/hooks/useUser.tsx b/apps/carbon/app/hooks/useUser.tsxindex 3f34594b51..f654ec6426 100644--- a/apps/carbon/app/hooks/useUser.tsx+++ b/apps/carbon/app/hooks/useUser.tsx@@ -4,6 +4,7 @@ type User = {email: string;firstName: string;lastName: string;+ avatarUrl: string | null;};export function useUser() {@@ -21,6 +22,7 @@ function isUser(value: any): value is User {return (typeof value.email === "string" &&typeof value.firstName === "string" &&- typeof value.lastName === "string"+ typeof value.lastName === "string" &&+ "avatarUrl" in value);}diff --git a/apps/carbon/app/modules/Account/Password/PasswordForm/PasswordForm.tsx b/apps/carbon/app/modules/Account/Password/PasswordForm/PasswordForm.tsxnew file mode 100644index 0000000000..ed7ba16379--- /dev/null+++ b/apps/carbon/app/modules/Account/Password/PasswordForm/PasswordForm.tsx@@ -0,0 +1,50 @@+import { Box, Heading, Text, VStack } from "@chakra-ui/react";+import { useRef, useState } from "react";+import { ValidatedForm } from "remix-validated-form";+import { Password, Submit } from "~/components/Form";+import { accountPasswordValidator } from "~/services/account";++const PasswordForm = () => {+ const [passwordsMatch, setPasswordsMatch] = useState(false);+ const passwordRef = useRef<HTMLInputElement>(null);+ const confirmPasswordRef = useRef<HTMLInputElement>(null);++ const onPasswordChange = () => {+ if (passwordRef.current && confirmPasswordRef.current) {+ setPasswordsMatch(+ passwordRef.current.value.length >= 6 &&+ confirmPasswordRef.current.value.length >= 6 &&+ passwordRef.current.value === confirmPasswordRef.current.value+ );+ }+ };++ return (+ <Box w="full">+ <ValidatedForm+ method="post"+ action="/app/account/password"+ validator={accountPasswordValidator}+ >+ <VStack spacing={4} my={4} w="full" alignItems="start" maxW={440}>+ <Password name="currentPassword" label="Current Password" />+ <Password+ ref={passwordRef}+ onChange={onPasswordChange}+ name="password"+ label="New Password"+ />+ <Password+ ref={confirmPasswordRef}+ onChange={onPasswordChange}+ name="confirmPassword"+ label="Confirm Password"+ />+ <Submit disabled={!passwordsMatch}>Update Password</Submit>+ </VStack>+ </ValidatedForm>+ </Box>+ );+};++export default PasswordForm;diff --git a/apps/carbon/app/modules/Account/Password/PasswordForm/index.ts b/apps/carbon/app/modules/Account/Password/PasswordForm/index.tsnew file mode 100644index 0000000000..dbb46e1458--- /dev/null+++ b/apps/carbon/app/modules/Account/Password/PasswordForm/index.ts@@ -0,0 +1,3 @@+import PasswordForm from "./PasswordForm";++export default PasswordForm;diff --git a/apps/carbon/app/modules/Account/Password/index.ts b/apps/carbon/app/modules/Account/Password/index.tsnew file mode 100644index 0000000000..70279d84d7--- /dev/null+++ b/apps/carbon/app/modules/Account/Password/index.ts@@ -0,0 +1,3 @@+import PasswordForm from "./PasswordForm";++export { PasswordForm };diff --git a/apps/carbon/app/modules/Account/Personal/PersonalDataForm/PersonalDataForm.tsx b/apps/carbon/app/modules/Account/Personal/PersonalDataForm/PersonalDataForm.tsxnew file mode 100644index 0000000000..2ef8720eb1--- /dev/null+++ b/apps/carbon/app/modules/Account/Personal/PersonalDataForm/PersonalDataForm.tsx@@ -0,0 +1,30 @@+import { Box, Grid, VStack } from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import { Submit } from "~/components/Form";+import type { PersonalData } from "~/modules/Account/types";+import { accountPersonalDataValidator } from "~/services/account";++type PersonalDataFormProps = {+ personalData: PersonalData;+};++const PersonalDataForm = ({ personalData }: PersonalDataFormProps) => {+ return (+ <Box w="full">+ <ValidatedForm+ method="post"+ action="/app/account/personal"+ validator={accountPersonalDataValidator}+ defaultValues={personalData}+ >+ <VStack alignItems="start" w="full" spacing={4} mt={4}>+ <Grid gridTemplateColumns="1fr 1fr" gridColumnGap={4} w="full"></Grid>++ <Submit>Save</Submit>+ </VStack>+ </ValidatedForm>+ </Box>+ );+};++export default PersonalDataForm;diff --git a/apps/carbon/app/modules/Account/Personal/PersonalDataForm/index.ts b/apps/carbon/app/modules/Account/Personal/PersonalDataForm/index.tsnew file mode 100644index 0000000000..d0cc549b77--- /dev/null+++ b/apps/carbon/app/modules/Account/Personal/PersonalDataForm/index.ts@@ -0,0 +1,3 @@+import PersonalDataForm from "./PersonalDataForm";++export default PersonalDataForm;diff --git a/apps/carbon/app/modules/Account/Personal/index.ts b/apps/carbon/app/modules/Account/Personal/index.tsnew file mode 100644index 0000000000..dbc5085fa4--- /dev/null+++ b/apps/carbon/app/modules/Account/Personal/index.ts@@ -0,0 +1,3 @@+import PersonalDataForm from "./PersonalDataForm";++export { PersonalDataForm };diff --git a/apps/carbon/app/modules/Account/Profile/ProfileForm/ProfileForm.tsx b/apps/carbon/app/modules/Account/Profile/ProfileForm/ProfileForm.tsxnew file mode 100644index 0000000000..41ebc047a3--- /dev/null+++ b/apps/carbon/app/modules/Account/Profile/ProfileForm/ProfileForm.tsx@@ -0,0 +1,34 @@+import { Box, Grid, VStack } from "@chakra-ui/react";+import { ValidatedForm } from "remix-validated-form";+import { Hidden, Input, Submit, TextArea } from "~/components/Form";+import type { User } from "~/modules/Users/types";+import { accountProfileValidator } from "~/services/account";++type ProfileFormProps = {+ user: User;+};++const ProfileForm = ({ user }: ProfileFormProps) => {+ return (+ <Box w="full">+ <ValidatedForm+ method="post"+ action="/app/account/profile"+ validator={accountProfileValidator}+ defaultValues={user}+ >+ <VStack spacing={4} my={4} w="full" alignItems="start">+ <Grid gridTemplateColumns="1fr 1fr" gridColumnGap={4} w="full">+ <Input name="firstName" label="First Name" />+ <Input name="lastName" label="Last Name" />+ </Grid>+ <TextArea name="about" label="About" characterLimit={160} my={2} />+ <Hidden name="intent" value="about" />+ <Submit>Save</Submit>+ </VStack>+ </ValidatedForm>+ </Box>+ );+};++export default ProfileForm;diff --git a/apps/carbon/app/modules/Account/Profile/ProfileForm/index.ts b/apps/carbon/app/modules/Account/Profile/ProfileForm/index.tsnew file mode 100644index 0000000000..445eac517e--- /dev/null+++ b/apps/carbon/app/modules/Account/Profile/ProfileForm/index.ts@@ -0,0 +1,3 @@+import ProfileForm from "./ProfileForm";++export default ProfileForm;diff --git a/apps/carbon/app/modules/Account/Profile/ProfilePhotoForm/ProfilePhotoForm.tsx b/apps/carbon/app/modules/Account/Profile/ProfilePhotoForm/ProfilePhotoForm.tsxnew file mode 100644index 0000000000..6e5bce9263--- /dev/null+++ b/apps/carbon/app/modules/Account/Profile/ProfilePhotoForm/ProfilePhotoForm.tsx@@ -0,0 +1,100 @@+import { useNotification } from "@carbon/react";+import { Button, Input, InputGroup, VStack } from "@chakra-ui/react";+import { useSubmit } from "@remix-run/react";+import type { ChangeEvent } from "react";+import { useRef } from "react";+import { Avatar } from "~/components/Avatar";+import { useSupabase } from "~/lib/supabase";+import type { Account } from "~/modules/Account/types";++type ProfilePhotoFormProps = {+ user: Account;+};++const ProfilePhotoForm = ({ user }: ProfilePhotoFormProps) => {+ const { supabase } = useSupabase();+ const fileInputRef = useRef<HTMLInputElement>(null);+ const notification = useNotification();+ const submit = useSubmit();++ const uploadImage = async (e: ChangeEvent<HTMLInputElement>) => {+ if (e.target.files && supabase) {+ const avatarFile = e.target.files[0];+ const fileExtension = avatarFile.name.substring(+ avatarFile.name.lastIndexOf(".") + 1+ );++ const imageUpload = await supabase.storage+ .from("avatars")+ .upload(`${user.id}.${fileExtension}`, avatarFile, {+ cacheControl: `${12 * 60 * 60}`,+ upsert: true,+ });++ if (imageUpload.error) {+ notification.copyableError(imageUpload.error, "Failed to upload image");+ }++ if (imageUpload.data?.path) {+ submitAvatarUrl(imageUpload.data.path);+ }+ }+ };++ const deleteImage = async () => {+ if (supabase) {+ const imageDelete = await supabase.storage+ .from("avatars")+ .remove([`${user.id}.png`]);++ if (imageDelete.error) {+ notification.copyableError(imageDelete.error, "Failed to remove image");+ }++ submitAvatarUrl(null);+ }+ };++ const submitAvatarUrl = (path: string | null) => {+ const formData = new FormData();+ formData.append("intent", "photo");+ if (path) formData.append("path", path);+ submit(formData, {+ method: "post",+ action: "/app/account/profile",+ });+ };++ return (+ <VStack w="full" spacing={2} px={8}>+ <Avatar size="2xl" path={user?.avatarUrl} title={user?.fullName ?? ""} />+ <InputGroup w="auto">+ <Input+ ref={fileInputRef}+ id="avatar-upload"+ type="file"+ hidden+ accept="image/*"+ onChange={uploadImage}+ />+ <Button+ size="md"+ variant="solid"+ colorScheme="brand"+ onClick={() => {+ if (fileInputRef.current) fileInputRef.current.click();+ }}+ >+ {user.avatarUrl ? "Change" : "Upload"}+ </Button>+ </InputGroup>+ {user.avatarUrl && (+ <Button size="md" variant="outline" onClick={deleteImage}>+ Remove+ </Button>+ )}+ </VStack>+ );+};++export default ProfilePhotoForm;diff --git a/apps/carbon/app/modules/Account/Profile/ProfilePhotoForm/index.ts b/apps/carbon/app/modules/Account/Profile/ProfilePhotoForm/index.tsnew file mode 100644index 0000000000..2753c24268--- /dev/null+++ b/apps/carbon/app/modules/Account/Profile/ProfilePhotoForm/index.ts@@ -0,0 +1,3 @@+import ProfilePhotoForm from "./ProfilePhotoForm";++export default ProfilePhotoForm;diff --git a/apps/carbon/app/modules/Account/Profile/index.ts b/apps/carbon/app/modules/Account/Profile/index.tsnew file mode 100644index 0000000000..50bb56f55e--- /dev/null+++ b/apps/carbon/app/modules/Account/Profile/index.ts@@ -0,0 +1,4 @@+import ProfileForm from "./ProfileForm";+import ProfilePhotoForm from "./ProfilePhotoForm";++export { ProfileForm, ProfilePhotoForm };diff --git a/apps/carbon/app/modules/Account/index.ts b/apps/carbon/app/modules/Account/index.tsnew file mode 100644index 0000000000..f97d900f06--- /dev/null+++ b/apps/carbon/app/modules/Account/index.ts@@ -0,0 +1,3 @@+import useAccountSidebar from "./useAccountSidebar";++export { useAccountSidebar };diff --git a/apps/carbon/app/modules/Account/types.ts b/apps/carbon/app/modules/Account/types.tsnew file mode 100644index 0000000000..644302a57c--- /dev/null+++ b/apps/carbon/app/modules/Account/types.ts@@ -0,0 +1,7 @@+import type { getAccountById } from "~/services/account";++export type PersonalData = {};++export type Account = NonNullable<+ Awaited<ReturnType<typeof getAccountById>>["data"]+>;diff --git a/apps/carbon/app/modules/Account/useAccountSidebar.tsx b/apps/carbon/app/modules/Account/useAccountSidebar.tsxnew file mode 100644index 0000000000..0ac560ce57--- /dev/null+++ b/apps/carbon/app/modules/Account/useAccountSidebar.tsx@@ -0,0 +1,33 @@+import type { Route } from "~/types";++const accountRoutes: Route[] = [+ {+ name: "Profile",+ to: "/app/account/profile",+ },+ {+ name: "Personal",+ to: "/app/account/personal",+ },+ {+ name: "Password",+ to: "/app/account/password",+ },+ // {+ // name: "Notifications",+ // to: "/app/account/notifications",+ // },+ // {+ // name: "Security",+ // to: "/app/account/security",+ // },+ // {+ // name: "Settings",+ // to: "/app/account/settings",+ // },+];++export default function useAccountSidebar() {+ // TODO: filter links based on employee type+ return { links: accountRoutes };+}diff --git a/apps/carbon/app/modules/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsx b/apps/carbon/app/modules/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsxindex fbcaa3061a..b5b07ad46c 100644--- a/apps/carbon/app/modules/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsx+++ b/apps/carbon/app/modules/Users/Employees/EmployeePermissionsForm/EmployeePermissionsForm.tsx@@ -71,6 +71,7 @@ const EmployeePermissionsForm = ({<ValidatedFormvalidator={employeeValidator}method="post"+ action={`/app/users/employees/${initialValues.id}`}defaultValues={initialValues}><VStack spacing={4} alignItems="start">diff --git a/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsx b/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsxindex 52a30a464d..455ea5ec33 100644--- a/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsx+++ b/apps/carbon/app/modules/Users/Employees/EmployeesTable/EmployeesTable.tsx@@ -14,6 +14,7 @@ import { Table } from "~/components/Data";import { usePermissions } from "~/hooks";import type { Employee } from "~/modules/Users/types";import { BulkEditPermissionsForm } from "~/modules/Users/BulkEditPermissions";+import { Avatar } from "~/components/Avatar";type EmployeesTableProps = {data: Employee[];@@ -22,6 +23,7 @@ type EmployeesTableProps = {};const defaultColumnVisibility = {+ Avatar: false,user_firstName: false,user_lastName: false,};@@ -53,6 +55,16 @@ const EmployeesTable = memo(const columns = useMemo<ColumnDef<typeof rows[number]>[]>(() => {return [+ {+ header: "Avatar",+ cell: ({ row }) => (+ <Avatar+ size="sm"+ // @ts-ignore+ path={row.original.user?.avatarUrl}+ />+ ),+ },{accessorKey: "user.fullName",header: "Full Name",diff --git a/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsx b/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsxindex 053fda0002..607073fc75 100644--- a/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsx+++ b/apps/carbon/app/modules/Users/Groups/GroupsTable/GroupsTable.tsx@@ -1,15 +1,10 @@import { ActionMenu } from "@carbon/react";-import {- Avatar,- AvatarGroup,- Flex,- MenuItem,- VisuallyHidden,-} from "@chakra-ui/react";+import { AvatarGroup, Flex, MenuItem, VisuallyHidden } from "@chakra-ui/react";import { useNavigate } from "@remix-run/react";import { memo } from "react";import { BsPencilSquare } from "react-icons/bs";import { IoMdTrash } from "react-icons/io";+import { Avatar } from "~/components/Avatar";import { Table } from "~/components/Data";import { usePermissions } from "~/hooks";import type { Group } from "~/modules/Users/types";@@ -28,8 +23,13 @@ const GroupsTable = memo(({ data, count }: GroupsTableProps) => {name: row.data.name,isEmployeeTypeGroup: row.data.isEmployeeTypeGroup,members: row.data.users- .map((user) => `${user.firstName} ${user.lastName}`)- .concat(row.children.map((child) => child.data.name)),+ .map((user) => ({+ name: user.fullName,+ avatar: user.avatarUrl,+ }))+ .concat(+ row.children.map((child) => ({ name: child.data.name, avatar: null }))+ ),}));return (@@ -47,14 +47,19 @@ const GroupsTable = memo(({ data, count }: GroupsTableProps) => {// accessorKey: undefined, // makes the column unsortablecell: ({ row }) => (<AvatarGroup max={5} size="sm" spacing={-2}>- {row.original.members.map((name: string, index: number) => (- <Avatar- key={index}- name={name}- title={name}- colorScheme="gray"- />- ))}+ {row.original.members.map(+ (+ member: { name: string | null; avatar: string | null },+ index: number+ ) => (+ <Avatar+ key={index}+ name={member.name ?? undefined}+ title={member.name ?? undefined}+ path={member.avatar}+ />+ )+ )}</AvatarGroup>),},diff --git a/apps/carbon/app/routes/_auth.callback.tsx b/apps/carbon/app/routes/_auth.callback.tsxindex 6f36c8a665..e1398d69fb 100644--- a/apps/carbon/app/routes/_auth.callback.tsx+++ b/apps/carbon/app/routes/_auth.callback.tsx@@ -4,7 +4,7 @@ import { json, redirect } from "@remix-run/node";import type { LoaderArgs, ActionArgs } from "@remix-run/node";import { useFetcher } from "@remix-run/react";import { callbackValidator } from "~/services/auth/auth.form";-import { getSupabase } from "~/lib/supabase";+import { getSupabase, getSupabaseAdmin } from "~/lib/supabase";import { refreshAccessToken } from "~/services/auth";import { getUserByEmail } from "~/services/users";import {@@ -37,11 +37,7 @@ export async function action({ request }: ActionArgs): FormActionData {}const { refreshToken } = validation.data;-- // We should not trust what is sent from the client- // https://github.com/rphlmr/supa-fly-stack/issues/45const authSession = await refreshAccessToken(refreshToken);-if (!authSession) {return redirect("/",@@ -49,7 +45,6 @@ export async function action({ request }: ActionArgs): FormActionData {);}- // user has an account, skip creation and just commit the sessionconst user = await getUserByEmail(authSession.email);if (user?.data) {return redirect("/reset-password", {diff --git a/apps/carbon/app/routes/_auth.forgot-password.tsx b/apps/carbon/app/routes/_auth.forgot-password.tsxindex 3aa0894675..bb66103ad0 100644--- a/apps/carbon/app/routes/_auth.forgot-password.tsx+++ b/apps/carbon/app/routes/_auth.forgot-password.tsx@@ -22,6 +22,7 @@ import { getUserByEmail } from "~/services/users";import { assertIsPost } from "~/utils/http";import type { FormActionData, Result } from "~/types";import { error } from "~/utils/result";+import { getSupabaseAdmin } from "~/lib/supabase";export const meta: MetaFunction = () => ({title: "Carbon | Forgot Password",diff --git a/apps/carbon/app/routes/app.account.index.tsx b/apps/carbon/app/routes/app.account.index.tsxnew file mode 100644index 0000000000..ca6facd967--- /dev/null+++ b/apps/carbon/app/routes/app.account.index.tsx@@ -0,0 +1,5 @@+import { redirect } from "@remix-run/node";++export async function loader() {+ return redirect("/app/account/profile");+}diff --git a/apps/carbon/app/routes/app.account.notifications.tsx b/apps/carbon/app/routes/app.account.notifications.tsxnew file mode 100644index 0000000000..a55ba233d5--- /dev/null+++ b/apps/carbon/app/routes/app.account.notifications.tsx@@ -0,0 +1,3 @@+export default function AccountNotifications() {+ return <p>Profile</p>;+}diff --git a/apps/carbon/app/routes/app.account.password.tsx b/apps/carbon/app/routes/app.account.password.tsxnew file mode 100644index 0000000000..0323dd3c15--- /dev/null+++ b/apps/carbon/app/routes/app.account.password.tsx@@ -0,0 +1,72 @@+import type { ActionArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/router";+import { validationError } from "remix-validated-form";+import { PageTitle } from "~/components/Layout";+import { getSupabaseAdmin } from "~/lib/supabase";+import { PasswordForm } from "~/modules/Account/Password";+import { accountPasswordValidator } from "~/services/account";+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 { email, userId } = await requirePermissions(request, {});++ const validation = await accountPasswordValidator.validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const { currentPassword, password } = validation.data;++ const confirmPassword = await getSupabaseAdmin().auth.signInWithPassword({+ email,+ password: currentPassword,+ });++ if (confirmPassword.error || !("user" in confirmPassword.data)) {+ return json(+ {},+ await flash(request, error(null, "Current password is invalid"))+ );+ }++ const updatePassword = await getSupabaseAdmin().auth.admin.updateUserById(+ userId,+ {+ password,+ }+ );++ if (updatePassword.error) {+ return json(+ {},+ await flash(+ request,+ error(updatePassword.error, "Failed to update password")+ )+ );+ }++ return redirect(+ "/app",+ await flash(request, success("Succesfully updated password"))+ );+}++export default function AccountPassword() {+ return (+ <>+ <PageTitle+ title="Change Password"+ subtitle="Make sure it's at least 12 characters"+ />+ <PasswordForm />+ </>+ );+}diff --git a/apps/carbon/app/routes/app.account.personal.tsx b/apps/carbon/app/routes/app.account.personal.tsxnew file mode 100644index 0000000000..f864e8531a--- /dev/null+++ b/apps/carbon/app/routes/app.account.personal.tsx@@ -0,0 +1,14 @@+import { PageTitle } from "~/components/Layout";+import { PersonalDataForm } from "~/modules/Account/Personal";++export default function AccountPersonal() {+ return (+ <>+ <PageTitle+ title="Personal Data"+ subtitle="This information is private and stored in an encrypted format."+ />+ <PersonalDataForm personalData={{}} />+ </>+ );+}diff --git a/apps/carbon/app/routes/app.account.profile.tsx b/apps/carbon/app/routes/app.account.profile.tsxnew file mode 100644index 0000000000..1cb0cb1ea8--- /dev/null+++ b/apps/carbon/app/routes/app.account.profile.tsx@@ -0,0 +1,122 @@+import { Grid } from "@chakra-ui/react";+import type { ActionArgs, LoaderArgs } from "@remix-run/node";+import { redirect } from "@remix-run/node";+import { useLoaderData } from "@remix-run/react";+import { json } from "@remix-run/router";+import { validationError } from "remix-validated-form";+import { PageTitle } from "~/components/Layout";+import { ProfileForm, ProfilePhotoForm } from "~/modules/Account/Profile";+import {+ accountProfileValidator,+ getAccountById,+ updateAvatar,+ updatePublicAccount,+} from "~/services/account";+import { requirePermissions } from "~/services/auth";+import { flash } from "~/services/session";+import { assertIsPost } from "~/utils/http";+import { error, success } from "~/utils/result";++export async function loader({ request }: LoaderArgs) {+ const { client, userId } = await requirePermissions(request, {});++ if (!userId) {+ return redirect(+ "/app",+ await flash(request, error(undefined, "Could not authenticate request"))+ );+ }++ const user = await getAccountById(client, userId);+ if (user.error || !user.data) {+ return redirect(+ "/app",+ await flash(request, error(user.error, "Failed to get user"))+ );+ }++ return json({ user: user.data });+}++export async function action({ request }: ActionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {});+ const formData = await request.formData();++ if (formData.get("intent") === "about") {+ const validation = await accountProfileValidator.validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { firstName, lastName, about } = validation.data;++ const updateAccount = await updatePublicAccount(client, {+ id: userId,+ firstName,+ lastName,+ about,+ });+ if (updateAccount.error)+ return json(+ {},+ await flash(+ request,+ error(updateAccount.error, "Failed to update profile")+ )+ );++ return json({}, await flash(request, success("Updated profile")));+ }++ if (formData.get("intent") === "photo") {+ const path = formData.get("path");+ if (path === null || typeof path === "string") {+ const avatarUpdate = await updateAvatar(client, userId, path);+ if (avatarUpdate.error) {+ return redirect(+ "/app/account/profile",+ await flash(+ request,+ error(avatarUpdate.error, "Failed to update avatar")+ )+ );+ }++ return redirect(+ "/app/account/profile",+ await flash(request, success("Successfully updated avatar"))+ );+ } else {+ return redirect(+ "/app/account/profile",+ await flash(request, error(null, "Invalid avatar path"))+ );+ }+ }++ return null;+}++export default function AccountProfile() {+ const { user } = useLoaderData<typeof loader>();++ return (+ <>+ <PageTitle+ title="Profile"+ subtitle="This information will be displayed publicly so be careful what you+ share."+ />+ <Grid+ gridTemplateColumns={["1fr", "1fr auto"]}+ w="full"+ gridColumnGap={8}+ >+ <ProfileForm user={user} />+ <ProfilePhotoForm user={user} />+ </Grid>+ </>+ );+}diff --git a/apps/carbon/app/routes/app.account.security.tsx b/apps/carbon/app/routes/app.account.security.tsxnew file mode 100644index 0000000000..29e6066521--- /dev/null+++ b/apps/carbon/app/routes/app.account.security.tsx@@ -0,0 +1,3 @@+export default function AccountSecurity() {+ return <p>Security</p>;+}diff --git a/apps/carbon/app/routes/app.account.settings.tsx b/apps/carbon/app/routes/app.account.settings.tsxnew file mode 100644index 0000000000..5a1040ee4c--- /dev/null+++ b/apps/carbon/app/routes/app.account.settings.tsx@@ -0,0 +1,3 @@+export default function AccountSettings() {+ return <p>Settings</p>;+}diff --git a/apps/carbon/app/routes/app.account.tsx b/apps/carbon/app/routes/app.account.tsxnew file mode 100644index 0000000000..3508991107--- /dev/null+++ b/apps/carbon/app/routes/app.account.tsx@@ -0,0 +1,57 @@+import { useColor } from "@carbon/react";+import { Button, Grid, Text, VStack } from "@chakra-ui/react";+import type { MetaFunction } from "@remix-run/node";+import { Link, Outlet, useMatches } from "@remix-run/react";+import { ContentSidebar } from "~/components/Layout/Sidebar";+import { useAccountSidebar } from "~/modules/Account";++export const meta: MetaFunction = () => ({+ title: "Carbon | My Account",+});++export default function AccountRoute() {+ const { links } = useAccountSidebar();+ const matches = useMatches();+ const borderColor = useColor("gray.200");++ return (+ <Grid w="full" h="full" templateColumns="auto 1fr" overflow="auto">+ <ContentSidebar>+ <VStack spacing={2}>+ <VStack+ spacing={1}+ alignItems="start"+ borderBottomStyle={"solid"}+ borderBottomWidth={1}+ borderBottomColor={borderColor}+ px={2}+ py={4}+ w="full"+ >+ {links.map((route) => {+ const isActive = matches.some((match) =>+ match.pathname.includes(route.to)+ );+ return (+ <Button+ key={route.name}+ as={Link}+ to={route.to}+ variant={isActive ? "solid" : "ghost"}+ fontWeight={isActive ? "bold" : "normal"}+ justifyContent="start"+ w="full"+ >+ {route.name}+ </Button>+ );+ })}+ </VStack>+ </VStack>+ </ContentSidebar>+ <VStack w="full" h="full" spacing={0} p={8}>+ <Outlet />+ </VStack>+ </Grid>+ );+}diff --git a/apps/carbon/app/routes/app.tsx b/apps/carbon/app/routes/app.tsxindex 342f10f269..e72f21b9b8 100644--- a/apps/carbon/app/routes/app.tsx+++ b/apps/carbon/app/routes/app.tsx@@ -5,7 +5,7 @@ import type { LoaderArgs } from "@remix-run/node";import { json } from "@remix-run/node";import { Outlet, useLoaderData } from "@remix-run/react";import { useEffect } from "react";-import { IconSidebar, Topbar } from "~/components/Navigation";+import { IconSidebar, Topbar } from "~/components/Layout";import { getSupabase, SupabaseProvider } from "~/lib/supabase";import { getPermissions, getUser } from "~/services/users";import {diff --git a/apps/carbon/app/routes/app.users.tsx b/apps/carbon/app/routes/app.users.tsxindex 49508ddeeb..7e82820764 100644--- a/apps/carbon/app/routes/app.users.tsx+++ b/apps/carbon/app/routes/app.users.tsx@@ -2,7 +2,7 @@ import { useColor } from "@carbon/react";import { Button, Grid, Text, VStack } from "@chakra-ui/react";import type { MetaFunction } from "@remix-run/node";import { Link, Outlet, useMatches } from "@remix-run/react";-import { ContentSidebar } from "~/components/Navigation/Sidebar";+import { ContentSidebar } from "~/components/Layout/Sidebar";import { useUsersSidebar } from "~/modules/Users";export const meta: MetaFunction = () => ({diff --git a/apps/carbon/app/services/account/account.form.ts b/apps/carbon/app/services/account/account.form.tsnew file mode 100644index 0000000000..c0efda5ca7--- /dev/null+++ b/apps/carbon/app/services/account/account.form.ts@@ -0,0 +1,33 @@+import { withZod } from "@remix-validated-form/with-zod";+import { z } from "zod";++export const accountProfileValidator = withZod(+ z.object({+ firstName: z.string().min(1, { message: "First name is required" }),+ lastName: z.string().min(1, { message: "Last name is required" }),+ about: z.string(),+ })+);++export const accountPasswordValidator = withZod(+ z+ .object({+ currentPassword: z+ .string()+ .min(6, { message: "Current password is required" }),+ password: z.string().min(6, { message: "Password is required" }),+ confirmPassword: z+ .string()+ .min(6, { message: "Confirm password is required" }),+ })+ .superRefine(({ confirmPassword, password }, ctx) => {+ if (confirmPassword !== password) {+ ctx.addIssue({+ code: "custom",+ message: "The passwords did not match",+ });+ }+ })+);++export const accountPersonalDataValidator = withZod(z.object({}));diff --git a/apps/carbon/app/services/account/account.server.ts b/apps/carbon/app/services/account/account.server.tsnew file mode 100644index 0000000000..045f5b1fc1--- /dev/null+++ b/apps/carbon/app/services/account/account.server.ts@@ -0,0 +1,42 @@+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";++export async function getAccountById(+ client: SupabaseClient<Database>,+ id: string+) {+ return client.from("user").select("*").eq("id", id).single();+}++export async function updateAvatar(+ client: SupabaseClient<Database>,+ userId: string,+ avatarUrl: string | null+) {+ return client+ .from("user")+ .update({+ avatarUrl,+ })+ .eq("id", userId);+}++export async function updatePublicAccount(+ client: SupabaseClient<Database>,+ args: {+ id: string;+ firstName: string;+ lastName: string;+ about: string;+ }+) {+ const { id, firstName, lastName, about } = args;+ return client+ .from("user")+ .update({+ firstName,+ lastName,+ about,+ })+ .eq("id", id);+}diff --git a/apps/carbon/app/services/account/index.ts b/apps/carbon/app/services/account/index.tsnew file mode 100644index 0000000000..e628878620--- /dev/null+++ b/apps/carbon/app/services/account/index.ts@@ -0,0 +1,2 @@+export * from "./account.form";+export * from "./account.server";diff --git a/apps/carbon/app/services/auth/auth.server.ts b/apps/carbon/app/services/auth/auth.server.tsindex 91351d9b92..a8c4867dc2 100644--- a/apps/carbon/app/services/auth/auth.server.ts+++ b/apps/carbon/app/services/auth/auth.server.ts@@ -1,5 +1,9 @@+import type { Database } from "@carbon/database";import { redirect } from "@remix-run/node";-import type { AuthSession as SupabaseAuthSession } from "@supabase/supabase-js";+import type {+ AuthSession as SupabaseAuthSession,+ SupabaseClient,+} from "@supabase/supabase-js";import { SERVER_URL } from "~/config/env";import { REFRESH_ACCESS_TOKEN_THRESHOLD } from "~/config/env";import { getSupabase, getSupabaseAdmin } from "~/lib/supabase";@@ -73,11 +77,16 @@ export async function requirePermissions(update?: string | string[];delete?: string | string[];}-) {- const { accessToken } = await requireAuthSession(request);+): Promise<{+ client: SupabaseClient<Database>;+ email: string;+ userId: string;+}> {+ const { accessToken, email, userId } = await requireAuthSession(request);const client = getSupabase(accessToken);// early exit if no requiredPermissions are required- if (Object.keys(requiredPermissions).length === 0) return { client };+ if (Object.keys(requiredPermissions).length === 0)+ return { client, email, userId };const myPermissions = await getPermissions(request, client);@@ -109,7 +118,7 @@ export async function requirePermissions();}- return { client };+ return { client, email, userId };}export async function resetPassword(accessToken: string, password: string) {@@ -157,8 +166,7 @@ export async function refreshAccessToken(): Promise<AuthSession | null> {if (!refreshToken) return null;- const { data, error } = await getSupabaseAdmin().auth.setSession({- access_token: "",+ const { data, error } = await getSupabaseAdmin().auth.refreshSession({refresh_token: refreshToken,});diff --git a/apps/carbon/app/services/users/users.server.ts b/apps/carbon/app/services/users/users.server.tsindex 366e717d99..7c06eae0be 100644--- a/apps/carbon/app/services/users/users.server.ts+++ b/apps/carbon/app/services/users/users.server.ts@@ -61,6 +61,7 @@ export async function createEmployeeAccount(email,firstName,lastName,+ avatarUrl: null,});if (insertUser.error)@@ -149,7 +150,7 @@ export async function getEmployees(let query = client.from("employee").select(- "user!inner(id, fullName, firstName, lastName, email), employeeType!inner(name)",+ "user!inner(id, fullName, firstName, lastName, email, avatarUrl), employeeType!inner(name)",{ count: "exact" });@@ -325,7 +326,7 @@ export async function getUserByEmail(email: string) {export async function getUsers(client: SupabaseClient<Database>) {return client.from("user")- .select("id, firstName, lastName, fullName, email")+ .select("id, firstName, lastName, fullName, email, avatarUrl").order("lastName");}diff --git a/apps/carbon/app/utils/result.ts b/apps/carbon/app/utils/result.tsindex a50698c5a4..13dc1398b6 100644--- a/apps/carbon/app/utils/result.ts+++ b/apps/carbon/app/utils/result.ts@@ -2,7 +2,7 @@ import logger from "~/lib/logger";import type { Result } from "~/types";export function error(error: any, message = "Request failed"): Result {- logger.error({ error, message });+ if (error) logger.error({ error, message });return {success: false,diff --git a/apps/carbon/package.json b/apps/carbon/package.jsonindex 6400de53f1..15f938b557 100644--- a/apps/carbon/package.json+++ b/apps/carbon/package.json@@ -28,7 +28,7 @@"@supabase/supabase-js": "^2.2.1","@tanstack/react-table": "^8.7.3","@vercel/node": "^2.8.0",- "bullmq": "~2.1.0",+ "bullmq": "~3.5.1","framer-motion": "^7.6.19","lodash.words": "^4.2.0","lodash.debounce": "^4.0.8",diff --git a/apps/carbon/public/serviceWorker.js b/apps/carbon/public/serviceWorker.jsnew file mode 100644index 0000000000..2cef0ad515--- /dev/null+++ b/apps/carbon/public/serviceWorker.js@@ -0,0 +1,31 @@+self.addEventListener("fetch", (event) => {+ let url = new URL(event.request.url);+ let method = event.request.method;++ // any non GET request is ignored+ if (method.toLowerCase() !== "get") return;++ // If the request is for the favicons, fonts, or the built files (which are hashed in the name)+ if (+ url.pathname.contains("logo") ||+ url.pathname.contains("storage/v1/object/public/avatars")+ ) {+ event.respondWith(+ // we will open the assets cache+ caches.open("assets").then(async (cache) => {+ // if the request is cached we will use the cache+ let cacheResponse = await cache.match(event.request);+ if (cacheResponse) return cacheResponse;++ // if it's not cached we will run the fetch, cache it and return it+ // this way the next time this asset it's needed it will load from the cache+ let fetchResponse = await fetch(event.request);+ cache.put(event.request, fetchResponse.clone());++ return fetchResponse;+ })+ );+ }++ return;+});diff --git a/packages/carbon-database/prisma/migrations/20221122043019_user/migration.sql b/packages/carbon-database/prisma/migrations/20221122043019_user/migration.sqlindex 402f2ca213..db2d89f9a5 100644--- a/packages/carbon-database/prisma/migrations/20221122043019_user/migration.sql+++ b/packages/carbon-database/prisma/migrations/20221122043019_user/migration.sql@@ -4,6 +4,8 @@ CREATE TABLE "user" ("firstName" TEXT NOT NULL,"lastName" TEXT NOT NULL,"fullName" TEXT GENERATED ALWAYS AS ("firstName" || ' ' || "lastName") STORED,+ "about" TEXT NOT NULL DEFAULT '',+ "avatarUrl" TEXT,"emailVerified" TIMESTAMP(3),"createdAt" TIMESTAMP(3) NOT NULL DEFAULT NOW(),"updatedAt" TIMESTAMP(3),@@ -12,7 +14,7 @@ CREATE TABLE "user" ();CREATE UNIQUE INDEX "user_email_key" ON "user"("email");-CREATE UNIQUE INDEX "user_fullName_key" ON "user"("fullName");+CREATE INDEX "user_fullName_key" ON "user"("fullName");ALTER TABLE "user" ENABLE ROW LEVEL SECURITY;diff --git a/packages/carbon-database/prisma/migrations/20221202032804_employee/migration.sql b/packages/carbon-database/prisma/migrations/20221202032804_employee/migration.sqlindex 133f69433e..70edca501f 100644--- a/packages/carbon-database/prisma/migrations/20221202032804_employee/migration.sql+++ b/packages/carbon-database/prisma/migrations/20221202032804_employee/migration.sql@@ -12,3 +12,10 @@ ALTER TABLE "employee" ENABLE ROW LEVEL SECURITY;CREATE POLICY "Only claims admin can view/modify employees" ON "employee" FOR ALL USING (is_claims_admin());CREATE POLICY "Anyone that's authenticated can view employees" ON "employee" FOR SELECT USING (auth.role() = 'authenticated');+CREATE TABLE "employeePersonalData" (+ "id" TEXT NOT NULL,+++ CONSTRAINT "employeePersonalData_pkey" PRIMARY KEY ("id"),+ CONSTRAINT "employeePersonalData_id_fkey" FOREIGN KEY ("id") REFERENCES "employee"("id") ON DELETE CASCADE ON UPDATE NO ACTION+)\ No newline at end of filediff --git a/packages/carbon-database/prisma/migrations/20221223438102_buckets/migration.sql b/packages/carbon-database/prisma/migrations/20221223438102_buckets/migration.sqlnew file mode 100644index 0000000000..aa09a17589--- /dev/null+++ b/packages/carbon-database/prisma/migrations/20221223438102_buckets/migration.sql@@ -0,0 +1,32 @@+INSERT INTO storage.buckets (id, name, public)+VALUES+ ('public', 'public', true),+ ('avatars', 'avatars', true),+ ('private', 'private', false);++CREATE POLICY "Anyone can view avatars"+ON storage.objects FOR SELECT USING (+ bucket_id = 'avatars'+);++CREATE POLICY "Users can delete their own avatars"+ON storage.objects FOR DELETE USING (+ bucket_id = 'avatars'+ and (auth.role() = 'authenticated')+ and storage.filename(name) like concat(auth.uid()::text, '%')+);++CREATE POLICY "Users can update their own avatars"+ON storage.objects FOR UPDATE USING (+ bucket_id = 'avatars'+ and (auth.role() = 'authenticated')+ and storage.filename(name) like concat(auth.uid()::text, '%')+);++CREATE POLICY "Users can insert their own avatars"+ON storage.objects FOR INSERT with check (+ bucket_id = 'avatars'+ and (auth.role() = 'authenticated')+ and storage.filename(name) like concat(auth.uid()::text, '%')+);+diff --git a/packages/carbon-database/prisma/schema.prisma b/packages/carbon-database/prisma/schema.prismaindex c910341a63..041428327f 100644--- a/packages/carbon-database/prisma/schema.prisma+++ b/packages/carbon-database/prisma/schema.prisma@@ -53,12 +53,14 @@ model user {email String @uniquefirstName StringlastName String- fullName String? @unique @default(dbgenerated("((\"firstName\" || ' '::text) || \"lastName\")"))+ fullName String? @default(dbgenerated("((\"firstName\" || ' '::text) || \"lastName\")"))emailVerified DateTime?createdAt DateTime @default(now())updatedAt DateTime?employee employee?membership membership[]++ @@index([fullName], map: "user_fullName_key")}model group {@@ -82,4 +84,7 @@ model membership {user user? @relation(fields: [memberUserId], references: [id], onDelete: Cascade)@@unique([groupId, memberGroupId, memberUserId], map: "uq_membership")+ @@index([groupId], map: "index_membership_groupid")+ @@index([memberGroupId], map: "index_membership_membergroupid")+ @@index([memberUserId], map: "index_membership_memberuserid")}diff --git a/packages/carbon-database/src/types.ts b/packages/carbon-database/src/types.tsindex af454aa5b8..6303ef299d 100644--- a/packages/carbon-database/src/types.ts+++ b/packages/carbon-database/src/types.ts@@ -55,6 +55,17 @@ export interface Database {employeeTypeId?: string}}+ employeePersonalData: {+ Row: {+ id: string+ }+ Insert: {+ id: string+ }+ Update: {+ id?: string+ }+ }employeeType: {Row: {id: string@@ -186,6 +197,8 @@ export interface Database {firstName: stringlastName: stringfullName: string | null+ about: string+ avatarUrl: string | nullemailVerified: string | nullcreatedAt: stringupdatedAt: string | null@@ -196,6 +209,8 @@ export interface Database {firstName: stringlastName: stringfullName?: string | null+ about?: string+ avatarUrl?: string | nullemailVerified?: string | nullcreatedAt?: stringupdatedAt?: string | null@@ -206,6 +221,8 @@ export interface Database {firstName?: stringlastName?: stringfullName?: string | null+ about?: string+ avatarUrl?: string | nullemailVerified?: string | nullcreatedAt?: stringupdatedAt?: string | nulldiff --git a/packages/carbon-redis/package.json b/packages/carbon-redis/package.jsonindex 7f96187013..0dcbc6d425 100644--- a/packages/carbon-redis/package.json+++ b/packages/carbon-redis/package.json@@ -22,6 +22,7 @@"ioredis": "^5.2.4"},"devDependencies": {+ "@carbon/logger": "*","@carbon/tsconfig": "*","@types/node": "^16.17.1","@types/ioredis": "^5.0.0",diff --git a/yarn.lock b/yarn.lockindex 510566d441..a79389919f 100644--- a/yarn.lock+++ b/yarn.lock@@ -4181,25 +4181,10 @@ bufferutil@^4.0.1:dependencies:node-gyp-build "^4.3.0"- version "2.0.1"- resolved "https://registry.yarnpkg.com/bullmq/-/bullmq-2.0.1.tgz#ad65598033317614e051be5803dc140efa9f7587"- integrity sha512-i6RtXKjg4B0IeEEB8AQMrrSIEgm7VCL92cgv4sOXrBSIBdBJjmvowVJ5tPF0+NBM7UpKFJCl72Go8XU1GK/uVg==- dependencies:- cron-parser "^4.6.0"- get-port "6.1.2"- glob "^8.0.3"- ioredis "^5.2.2"- lodash "^4.17.21"- msgpackr "^1.6.2"- semver "^7.3.7"- tslib "^2.0.0"- uuid "^9.0.0"--bullmq@~2.1.0:- version "2.1.3"- resolved "https://registry.yarnpkg.com/bullmq/-/bullmq-2.1.3.tgz#6bb1e99c94b27dc4d72a18b1549d260a00edc5f5"- integrity sha512-sOuPHbCWegOnC0uKC1i8L6njmiDquenkStMXdpCzh+xrHEB4AxOFVhuM8SchmnjcJUBnW1lVe+SBc1vMNyR1ZQ==+bullmq@~3.5.1:+ version "3.5.1"+ resolved "https://registry.yarnpkg.com/bullmq/-/bullmq-3.5.1.tgz#253032396e9fb30d63336ad28ae2eaeffb37de41"+ integrity sha512-QxQnSIPBmEVq/bM1wxmMdh9RS4oNyUNeCvoTegr2EgtlNYToCkLgHAkM56JhaRlffo9ExNiWfVFJpXLWDfK0Fw==dependencies:cron-parser "^4.6.0"glob "^8.0.3"@@ -6596,11 +6581,6 @@ get-package-type@^0.1.0:resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a"integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==- version "6.1.2"- resolved "https://registry.yarnpkg.com/get-port/-/get-port-6.1.2.tgz#c1228abb67ba0e17fb346da33b15187833b9c08a"- integrity sha512-BrGGraKm2uPqurfGVj/z97/zv8dPleC6x9JBNRTrDNtCkkRF4rPwrQXFgL7+I+q8QSdU4ntLQX2D7KIxSy8nGw==-get-port@^5.1.1:version "5.1.1"resolved "https://registry.yarnpkg.com/get-port/-/get-port-5.1.1.tgz#0469ed07563479de6efb986baf053dcd7d4e3193"