Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

Feat(crm): Backport sales

Anthony Rimet94c898026e9e
diff --git a/src/Header.tsx b/src/Header.tsx
index f5405a24..aa9319cf 100644
--- a/src/Header.tsx
+++ b/src/Header.tsx
@@ -1,11 +1,11 @@
import SettingsIcon from '@mui/icons-material/Settings';
+import PeopleIcon from '@mui/icons-material/People';
import {
AppBar,
Box,
ListItemIcon,
ListItemText,
MenuItem,
- MenuList,
Tab,
Tabs,
Toolbar,
@@ -98,23 +98,14 @@ const Header = () => {
to="/deals"
value="/deals"
/>
- {permissions === 'admin' && (
- <Tab
- label={'Sales Team'}
- component={Link}
- to="/sales"
- value="/sales"
- />
- )}
</Tabs>
</Box>
<Box display="flex" alignItems="center">
<LoadingIndicator />
<UserMenu>
- <MenuList>
- <ConfigurationMenu />
- <Logout />
- </MenuList>
+ <ConfigurationMenu />
+ {permissions === 'admin' && <UsersMenu />}
+ <Logout />
</UserMenu>
</Box>
</Box>
@@ -124,6 +115,18 @@ const Header = () => {
);
};
+const UsersMenu = () => {
+ const { onClose } = useUserMenu() ?? {};
+ return (
+ <MenuItem component={Link} to="/sales" onClick={onClose}>
+ <ListItemIcon>
+ <PeopleIcon fontSize="small" />
+ </ListItemIcon>
+ <ListItemText>Users</ListItemText>
+ </MenuItem>
+ );
+};
+
const ConfigurationMenu = () => {
const { onClose } = useUserMenu() ?? {};
return (
diff --git a/src/dataProvider.ts b/src/dataProvider.ts
index 17e09b10..23edd3b8 100644
--- a/src/dataProvider.ts
+++ b/src/dataProvider.ts
@@ -120,7 +120,7 @@ const dataProviderWithCustomMethods = {
id: Identifier,
data: Partial<Omit<SalesFormData, 'password'>>
) {
- const { email, first_name, last_name, administrator } = data;
+ const { email, first_name, last_name, administrator, disabled } = data;
const { data: sale, error } = await supabase.functions.invoke<Sale>(
'users',
@@ -132,6 +132,7 @@ const dataProviderWithCustomMethods = {
first_name,
last_name,
administrator,
+ disabled,
},
}
);
@@ -143,37 +144,6 @@ const dataProviderWithCustomMethods = {
return data;
},
- async transferAdministratorRole(from: Identifier, to: Identifier) {
- const { data: sales } = await baseDataProvider.getList('sales', {
- filter: { id: [from, to] },
- pagination: { page: 1, perPage: 2 },
- sort: { field: 'name', order: 'ASC' },
- });
-
- const fromSale = sales.find(sale => sale.id === from);
- const toSale = sales.find(sale => sale.id === to);
-
- if (!fromSale || !toSale) {
- return null;
- }
-
- await baseDataProvider.update('sales', {
- id: to,
- data: {
- administrator: true,
- },
- previousData: toSale,
- });
-
- const updatedUser = await baseDataProvider.update('sales', {
- id: from,
- data: {
- administrator: false,
- },
- previousData: fromSale,
- });
- return updatedUser.data;
- },
async unarchiveDeal(deal: Deal) {
// get all deals where stage is the same as the deal to unarchive
const { data: deals } = await baseDataProvider.getList<Deal>('deals', {
diff --git a/src/sales/SalesEdit.tsx b/src/sales/SalesEdit.tsx
index fa45d06a..3b032c3e 100644
--- a/src/sales/SalesEdit.tsx
+++ b/src/sales/SalesEdit.tsx
@@ -1,14 +1,11 @@
import { Card, Container, Typography } from '@mui/material';
import { useMutation } from '@tanstack/react-query';
import {
- DeleteWithConfirmButton,
- PasswordInput,
SaveButton,
SimpleForm,
Toolbar,
useDataProvider,
useEditController,
- useGetIdentity,
useNotify,
useRecordContext,
useRedirect,
@@ -19,21 +16,9 @@ import { Sale, SalesFormData } from '../types';
import { SalesInputs } from './SalesInputs';
function EditToolbar() {
- const { identity } = useGetIdentity();
- const record = useRecordContext<Sale>();
-
return (
<Toolbar sx={{ display: 'flex', justifyContent: 'space-between' }}>
<SaveButton />
-
- <DeleteWithConfirmButton
- disabled={record?.id === identity?.id}
- mutationOptions={{
- meta: {
- identity,
- },
- }}
- />
</Toolbar>
);
}
@@ -71,15 +56,10 @@ export function SalesEdit() {
<SimpleForm
toolbar={<EditToolbar />}
onSubmit={onSubmit as SubmitHandler<any>}
- defaultValues={record}
+ record={record}
>
<SaleEditTitle />
- <SalesInputs>
- <PasswordInput
- source="new_password"
- helperText={false}
- />
- </SalesInputs>
+ <SalesInputs />
</SimpleForm>
</Card>
</Container>
diff --git a/src/sales/SalesInputs.tsx b/src/sales/SalesInputs.tsx
index f68a389c..0f6b70bb 100644
--- a/src/sales/SalesInputs.tsx
+++ b/src/sales/SalesInputs.tsx
@@ -9,10 +9,9 @@ import { Sale } from '../types';
import { ReactNode } from 'react';
import { Stack } from '@mui/material';
-export function SalesInputs({ children }: { children: ReactNode }) {
+export function SalesInputs({ children }: { children?: ReactNode }) {
const { identity } = useGetIdentity();
const record = useRecordContext<Sale>();
-
return (
<Stack gap={1} sx={{ width: '100%' }}>
<TextInput
@@ -36,6 +35,11 @@ export function SalesInputs({ children }: { children: ReactNode }) {
readOnly={record?.id === identity?.id}
helperText={false}
/>
+ <BooleanInput
+ source="disabled"
+ readOnly={record?.id === identity?.id}
+ helperText={false}
+ />
</Stack>
);
}
diff --git a/src/sales/SalesList.tsx b/src/sales/SalesList.tsx
index 59589b80..d4da8e38 100644
--- a/src/sales/SalesList.tsx
+++ b/src/sales/SalesList.tsx
@@ -9,13 +9,12 @@ import {
TextField,
TopToolbar,
} from 'react-admin';
-import { TransferAdminRole } from './TransferAdminRole';
function SalesListActions() {
return (
<TopToolbar>
<ExportButton />
- <CreateButton variant="contained" label="New sales person" />
+ <CreateButton variant="contained" label="New user" />
</TopToolbar>
);
}
@@ -35,10 +34,9 @@ export function SalesList() {
<TextField source="last_name" />
<TextField source="email" />
<BooleanField source="administrator" FalseIcon={null} />
+ <BooleanField source="disabled" FalseIcon={null} />
</DatagridConfigurable>
</List>
-
- <TransferAdminRole />
</Stack>
);
}
diff --git a/src/sales/TransferAdminRole.tsx b/src/sales/TransferAdminRole.tsx
deleted file mode 100644
index f55db0f0..00000000
--- a/src/sales/TransferAdminRole.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import Card from '@mui/material/Card';
-import CardContent from '@mui/material/CardContent';
-import Link from '@mui/material/Link';
-import Stack from '@mui/material/Stack';
-import Typography from '@mui/material/Typography';
-import { MouseEvent, useCallback, useState } from 'react';
-import { useGetIdentity } from 'react-admin';
-import { TransferAdminRoleModal } from './TransferAdminRoleModal';
-
-export function TransferAdminRole() {
- const { identity } = useGetIdentity();
- const [showModal, setShowModal] = useState(false);
-
- const handleShowModal = (event: MouseEvent<HTMLAnchorElement>) => {
- event.preventDefault();
- setShowModal(true);
- };
-
- const handleCloseModal = useCallback(() => {
- setShowModal(false);
- }, []);
-
- if (!identity) {
- return null;
- }
-
- return (
- <>
- <Card>
- <CardContent>
- <Stack spacing={1}>
- <Typography variant="h5">
- Transfer Administrator Role
- </Typography>
-
- <Typography component="p" variant="body2">
- You are an administrator. Only administrators can
- manage access for account managers.
- </Typography>
-
- <Typography component="p" variant="body2">
- You can{' '}
- <Link
- onClick={handleShowModal}
- sx={{
- cursor: 'pointer',
- }}
- >
- transfer the administrator role
- </Link>{' '}
- to another account manager. By transfering the
- administrator role, you will no longer be able to
- manage access for other account managers.
- </Typography>
- </Stack>
- </CardContent>
- </Card>
-
- <TransferAdminRoleModal
- open={showModal}
- onClose={handleCloseModal}
- />
- </>
- );
-}
diff --git a/src/sales/TransferAdminRoleModal.tsx b/src/sales/TransferAdminRoleModal.tsx
deleted file mode 100644
index fb4b8cd5..00000000
--- a/src/sales/TransferAdminRoleModal.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-import Alert from '@mui/material/Alert';
-import Autocomplete from '@mui/material/Autocomplete';
-import Button from '@mui/material/Button';
-import CircularProgress from '@mui/material/CircularProgress';
-import Dialog from '@mui/material/Dialog';
-import DialogContent from '@mui/material/DialogContent';
-import DialogTitle from '@mui/material/DialogTitle';
-import Skeleton from '@mui/material/Skeleton';
-import { default as MuiTextField } from '@mui/material/TextField';
-import { DefaultError, useMutation } from '@tanstack/react-query';
-import {
- Toolbar,
- useDataProvider,
- useGetIdentity,
- useGetList,
- usePermissions,
-} from 'react-admin';
-import { Controller, SubmitHandler, useForm } from 'react-hook-form';
-import { useNavigate } from 'react-router';
-import { USER_STORAGE_KEY } from '../authProvider';
-import { CustomDataProvider } from '../dataProvider';
-import { Sale } from '../types';
-import { DialogCloseButton } from '../misc/DialogCloseButton';
-
-type TransferAdminRoleForm = {
- sale: Sale;
-};
-
-type TransferAdminRoleModalProps = {
- open: boolean;
- onClose(): void;
-};
-
-export function TransferAdminRoleModal({
- open,
- onClose,
-}: TransferAdminRoleModalProps) {
- const { identity } = useGetIdentity();
- const { refetch } = usePermissions();
- const dataProvider = useDataProvider<CustomDataProvider>();
- const navigate = useNavigate();
- const { control, handleSubmit } = useForm<TransferAdminRoleForm>();
-
- const mutation = useMutation<Sale, DefaultError, Sale>({
- mutationFn: async to => {
- if (!identity) {
- throw new Error('You are not logged in');
- }
-
- const user = await dataProvider.transferAdministratorRole(
- identity.id,
- to.id
- );
- if (!user) {
- throw new Error('Failed to transfer administrator role');
- }
-
- return user;
- },
- onSuccess: updatedUser => {
- localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(updatedUser));
-
- onClose();
-
- // Since the current user is no longer an administrator once they transfered the role, we need to redirect him to
- // home as he does not have access to the page anymore.
- navigate('/');
-
- // Since the current user is no longer an administrator once they transfered the role, we need to refresh their
- // identity and permissions.
- refetch();
- },
- onError: () => {},
- });
-
- const handleTransfer: SubmitHandler<TransferAdminRoleForm> = data => {
- if (!identity || !data.sale) {
- return;
- }
-
- mutation.mutate(data.sale);
- };
-
- return (
- <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
- <form onSubmit={handleSubmit(handleTransfer)}>
- <DialogCloseButton onClose={onClose} />
- <DialogTitle>Transfer Administrator Role</DialogTitle>
- <DialogContent>
- {mutation.error && (
- <Alert severity="error">
- Failed to transfer the administrator role
- </Alert>
- )}
-
- <SalesAutocomplete control={control} />
- </DialogContent>
- <Toolbar>
- <Button
- type="submit"
- color="error"
- variant="contained"
- disabled={mutation.isError || mutation.isPending}
- >
- {mutation.isPending ? (
- <CircularProgress size={16} />
- ) : (
- 'Transfer Role'
- )}
- </Button>
- </Toolbar>
- </form>
- </Dialog>
- );
-}
-
-function SalesAutocomplete({
- control,
-}: Pick<ReturnType<typeof useForm<TransferAdminRoleForm>>, 'control'>) {
- const {
- data: sales,
- error,
- isPending,
- } = useGetList('sales', {
- filter: { administrator: false },
- pagination: {
- page: 1,
- perPage: 1000,
- },
- sort: { field: 'first_name', order: 'ASC' },
- });
-
- if (isPending) {
- return <Skeleton />;
- }
-
- if (error) {
- return <Alert severity="error">Failed to fetch account managers</Alert>;
- }
-
- return (
- <Controller
- render={({ field: { onChange, value, ref } }) => (
- <Autocomplete<Sale>
- ref={ref}
- value={value ?? null}
- onChange={(_, newValue) => onChange(newValue)}
- options={sales}
- getOptionLabel={sale =>
- `${sale.first_name} ${sale.last_name}`
- }
- getOptionKey={sale => `${sale.id}`}
- renderInput={params => (
- <MuiTextField
- {...params}
- label="Account Manager"
- required
- />
- )}
- isOptionEqualToValue={(option, value) =>
- option.id === value?.id
- }
- />
- )}
- control={control}
- name="sale"
- />
- );
-}
diff --git a/src/settings/SettingsPage.tsx b/src/settings/SettingsPage.tsx
index a2216474..fcd0debf 100644
--- a/src/settings/SettingsPage.tsx
+++ b/src/settings/SettingsPage.tsx
@@ -129,7 +129,7 @@ const SettingsForm = ({
My info
</Typography>
</Stack>
- <Stack gap={1} mb={2}>
+ <Stack gap={2} mb={2}>
<ImageEditorField
source="avatar"
type="avatar"
@@ -197,7 +197,7 @@ const TextRender = ({
return <TextInput source={source} helperText={false} />;
}
return (
- <Labeled mb={'20px'}>
+ <Labeled sx={{ mb: 0 }}>
<TextField source={source} />
</Labeled>
);
diff --git a/src/settings/UpdatePassword.tsx b/src/settings/UpdatePassword.tsx
index 12061bf2..8d883826 100644
--- a/src/settings/UpdatePassword.tsx
+++ b/src/settings/UpdatePassword.tsx
@@ -6,15 +6,8 @@ import {
DialogTitle,
Stack,
TextField,
- Typography,
} from '@mui/material';
-import {
- Toolbar,
- useGetIdentity,
- useGetOne,
- useNotify,
- useUpdate,
-} from 'react-admin';
+import { Toolbar, useGetIdentity, useNotify, useUpdate } from 'react-admin';
import { useForm } from 'react-hook-form';
import { DialogCloseButton } from '../misc/DialogCloseButton';
@@ -43,9 +36,6 @@ export const UpdatePassword = ({
const newPassword = watch('newPassword');
const { identity } = useGetIdentity();
const notify = useNotify();
- const { data: dataUser, refetch } = useGetOne('sales', {
- id: identity?.id,
- });
if (!identity) return null;
@@ -63,7 +53,6 @@ export const UpdatePassword = ({
onSuccess: _ => {
notify('Your password has been updated');
setOpen(false);
- refetch();
reset();
},
onError: _ => {
@@ -86,19 +75,12 @@ export const UpdatePassword = ({
<DialogTitle>Change Password</DialogTitle>
<form onSubmit={handleSubmit(onSubmit)}>
<DialogContent>
- <Typography
- variant="caption"
- color="textSecondary"
- gutterBottom
- >
- Password for Jane Doe account is "demo"
- </Typography>
<Stack gap={1}>
<TextField
{...register('currentPassword', {
required: 'Current password is required',
- validate: value => value === dataUser.password,
})}
+ required
autoFocus
margin="dense"
label="Current Password"
@@ -107,7 +89,7 @@ export const UpdatePassword = ({
error={!!errors.currentPassword}
helperText={
errors.currentPassword
- ? 'Current password is incorrect'
+ ? 'Current password is required'
: ''
}
/>
@@ -122,6 +104,7 @@ export const UpdatePassword = ({
margin="dense"
label="New Password"
type="password"
+ required
fullWidth
error={!!errors.newPassword}
helperText={
@@ -138,6 +121,7 @@ export const UpdatePassword = ({
margin="dense"
label="Confirm New Password"
type="password"
+ required
fullWidth
error={!!errors.confirmNewPassword}
helperText={
diff --git a/src/types.ts b/src/types.ts
index 74759336..7c55c9b8 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -21,6 +21,7 @@ export type SalesFormData = {
first_name: string;
last_name: string;
administrator: boolean;
+ disabled: boolean;
};
export interface Sale extends RaRecord {
diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.ts
index 074187ee..34c2087c 100644
--- a/supabase/functions/users/index.ts
+++ b/supabase/functions/users/index.ts
@@ -26,6 +26,13 @@ function createErrorResponse(status: number, message: string) {
});
}
+async function updateSaleDisabled(user_id: string, disabled: boolean) {
+ return await supabaseServiceClient
+ .from('sales')
+ .update({ disabled })
+ .eq('user_id', user_id);
+}
+
async function updateSaleAdministrator(
user_id: string,
administrator: boolean
@@ -77,9 +84,8 @@ async function inviteUser(req: Request) {
}
async function patchUser(req: Request) {
- const { sales_id, email, first_name, last_name, administrator } =
+ const { sales_id, email, first_name, last_name, administrator, disabled } =
await req.json();
-
const { data: sale } = await supabaseServiceClient
.from('sales')
.select('*')
@@ -102,6 +108,7 @@ async function patchUser(req: Request) {
}
try {
+ await updateSaleDisabled(data.user.id, disabled);
const sale = await updateSaleAdministrator(data.user.id, administrator);
return new Response(