Skip to content

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

Feat(upload): Improve code for upload files

Anthony Rimet62442af9162f
diff --git a/src/authProvider.ts b/src/authProvider.ts
index fd211967..a4ede8ec 100644
--- a/src/authProvider.ts
+++ b/src/authProvider.ts
@@ -7,7 +7,7 @@ export const authProvider = supabaseAuthProvider(supabase, {
getIdentity: async user => {
const { data, error } = await supabase
.from('sales')
- .select('id, first_name, last_name')
+ .select('id, first_name, last_name, avatar')
.match({ user_id: user.id })
.single();
@@ -18,6 +18,7 @@ export const authProvider = supabaseAuthProvider(supabase, {
return {
id: data.id,
fullName: `${data.first_name} ${data.last_name}`,
+ avatar: data.avatar?.src,
};
},
getPermissions: async user => {
diff --git a/src/companies/CompanyInputs.tsx b/src/companies/CompanyInputs.tsx
index d0593a6b..357661e4 100644
--- a/src/companies/CompanyInputs.tsx
+++ b/src/companies/CompanyInputs.tsx
@@ -67,11 +67,12 @@ const CompanyDisplayInputs = () => {
return (
<Stack gap={2} flex={1} direction="row">
<ImageEditorField
- source="logo.src"
+ source="logo"
type="avatar"
width={60}
height={60}
emptyText={record?.name.charAt(0)}
+ linkPosition="bottom"
/>
<TextInput source="name" validate={required()} helperText={false} />
</Stack>
diff --git a/src/contacts/Avatar.tsx b/src/contacts/Avatar.tsx
index aa84fc46..31d81876 100644
--- a/src/contacts/Avatar.tsx
+++ b/src/contacts/Avatar.tsx
@@ -17,7 +17,7 @@ export const Avatar = (props: {
return (
<MuiAvatar
- src={record.avatar ?? undefined}
+ src={record.avatar?.src ?? undefined}
sx={{
width: props.width,
height: props.height,
diff --git a/src/dataProvider.ts b/src/dataProvider.ts
index 5b168556..24f30ede 100644
--- a/src/dataProvider.ts
+++ b/src/dataProvider.ts
@@ -1,14 +1,26 @@
import { supabaseDataProvider } from 'ra-supabase';
import {
+ CreateParams,
DataProvider,
GetListParams,
Identifier,
+ UpdateParams,
withLifecycleCallbacks,
} from 'react-admin';
import { getActivityLog } from './dataProvider/activity';
import { supabase } from './supabase';
-import { Deal, Sale, SalesFormData, SignUpData } from './types';
+import {
+ Contact,
+ ContactNote,
+ Deal,
+ RAFile,
+ Sale,
+ SalesFormData,
+ SignUpData,
+} from './types';
+import { getCompanyAvatar } from './misc/getCompanyAvatar';
+import { getContactAvatar } from './misc/getContactAvatar';
if (import.meta.env.VITE_SUPABASE_URL === undefined) {
throw new Error('Please set the VITE_SUPABASE_URL environment variable');
@@ -25,6 +37,44 @@ const baseDataProvider = supabaseDataProvider({
supabaseClient: supabase,
});
+const processCompanyLogo = async (params: any) => {
+ let logo = params.data.logo;
+
+ if (typeof logo !== 'object' || logo === null || !logo.src) {
+ logo = await getCompanyAvatar(params.data);
+ } else if (logo.rawFile instanceof File) {
+ await uploadToBucket(logo);
+ }
+
+ return {
+ ...params,
+ data: {
+ ...params.data,
+ logo,
+ },
+ };
+};
+
+async function processContactAvatar(
+ params: UpdateParams<Contact>
+): Promise<UpdateParams<Contact>>;
+
+async function processContactAvatar(
+ params: CreateParams<Contact>
+): Promise<CreateParams<Contact>>;
+
+async function processContactAvatar(
+ params: CreateParams<Contact> | UpdateParams<Contact>
+): Promise<CreateParams<Contact> | UpdateParams<Contact>> {
+ const { data } = params;
+ const avatarUrl = await getContactAvatar(data);
+
+ // Clone the data and modify the clone
+ const newData = { ...data, avatar: { src: avatarUrl || undefined } };
+
+ return { ...params, data: newData };
+}
+
const dataProviderWithCustomMethods = {
...baseDataProvider,
async signUp({ email, password, first_name, last_name }: SignUpData) {
@@ -165,46 +215,32 @@ export const dataProvider = withLifecycleCallbacks(
[
{
resource: 'contactNotes',
- beforeSave: async (data, _, __) => {
+ beforeSave: async (data: ContactNote, _, __) => {
if (data.attachments) {
for (const fi of data.attachments) {
- const response = await fetch(
- `${import.meta.env.VITE_SUPABASE_URL}/storage/v1/object/attachments/${fi.src}`,
- {
- method: 'HEAD',
- headers: {
- authorization: import.meta.env
- .VITE_SUPABASE_ANON_KEY,
- },
- }
- );
-
- if (response.status === 200) {
- continue;
- }
-
- const file = fi.rawFile;
- const fileExt = file.name.split('.').pop();
- const fileName = `${Math.random()}.${fileExt}`;
- const filePath = `${fileName}`;
- const { error: uploadError } = await supabase.storage
- .from('attachments')
- .upload(filePath, file);
-
- if (uploadError) {
- console.error('uploadError', uploadError);
- throw new Error('Failed to upload attachment');
- }
-
- fi.src = filePath;
+ await uploadToBucket(fi);
}
}
- console.log('data', data);
+ return data;
+ },
+ },
+ {
+ resource: 'sales',
+ beforeSave: async (data: Sale, _, __) => {
+ if (data.avatar) {
+ await uploadToBucket(data.avatar);
+ }
return data;
},
},
{
resource: 'contacts',
+ beforeCreate: async params => {
+ return processContactAvatar(params);
+ },
+ beforeUpdate: async params => {
+ return processContactAvatar(params);
+ },
beforeGetList: async params => {
return applyFullTextSearch([
'first_name',
@@ -229,6 +265,20 @@ export const dataProvider = withLifecycleCallbacks(
'stateAbbr',
])(params);
},
+ beforeCreate: async params => {
+ const createParams = await processCompanyLogo(params);
+
+ return {
+ ...createParams,
+ data: {
+ ...createParams.data,
+ created_at: new Date().toISOString(),
+ },
+ };
+ },
+ beforeUpdate: async params => {
+ return await processCompanyLogo(params);
+ },
},
{
resource: 'deals',
@@ -260,3 +310,43 @@ const applyFullTextSearch = (columns: string[]) => (params: GetListParams) => {
},
};
};
+
+const uploadToBucket = async (fi: RAFile) => {
+ if (!fi.src.startsWith('blob:') && !fi.src.startsWith('data:')) {
+ const response = await fetch(
+ `${import.meta.env.VITE_SUPABASE_URL}/storage/v1/object/attachments/${fi.src}`,
+ {
+ method: 'HEAD',
+ headers: {
+ authorization: import.meta.env.VITE_SUPABASE_ANON_KEY,
+ },
+ }
+ );
+
+ if (response.status === 200) {
+ return;
+ }
+ }
+
+ const file = fi.rawFile;
+ const fileExt = file.name.split('.').pop();
+ const fileName = `${Math.random()}.${fileExt}`;
+ const filePath = `${fileName}`;
+ const { error: uploadError } = await supabase.storage
+ .from('attachments')
+ .upload(filePath, file);
+
+ if (uploadError) {
+ console.error('uploadError', uploadError);
+ throw new Error('Failed to upload attachment');
+ }
+
+ const { data } = supabase.storage
+ .from('attachments')
+ .getPublicUrl(filePath);
+
+ fi.path = filePath;
+ fi.src = data.publicUrl;
+
+ return fi;
+};
diff --git a/src/misc/ImageEditorField.tsx b/src/misc/ImageEditorField.tsx
index e0051340..014525c4 100644
--- a/src/misc/ImageEditorField.tsx
+++ b/src/misc/ImageEditorField.tsx
@@ -7,8 +7,9 @@ import {
DialogActions,
DialogContent,
DialogTitle,
+ Link,
Stack,
- Tooltip,
+ Typography,
} from '@mui/material';
import 'cropperjs/dist/cropper.css';
import { useFieldValue } from 'ra-core';
@@ -21,35 +22,59 @@ import { DialogCloseButton } from './DialogCloseButton';
const ImageEditorField = (props: ImageEditorFieldProps) => {
const { getValues } = useFormContext();
- const imageUrl = getValues(props.source);
+ const source = getValues(props.source);
+ const imageUrl = source?.src;
const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const { type = 'image', emptyText, linkPosition = 'none' } = props;
+
const commonProps = {
src: imageUrl,
onClick: () => setIsDialogOpen(true),
style: { cursor: 'pointer' },
sx: {
...props.sx,
- width: props.width || (props.type === 'avatar' ? 50 : 200),
- height: props.height || (props.type === 'avatar' ? 50 : 200),
+ width: props.width || (type === 'avatar' ? 50 : 200),
+ height: props.height || (type === 'avatar' ? 50 : 200),
},
};
return (
- <div style={{ position: 'relative', display: 'inline-block' }}>
- <Tooltip title="Update image" followCursor>
+ <>
+ <Stack
+ direction={linkPosition === 'right' ? 'row' : 'column'}
+ alignItems={'center'}
+ gap={linkPosition === 'right' ? 2 : 0.5}
+ borderRadius={1}
+ p={props.backgroundImageColor ? 1 : 0}
+ sx={{
+ backgroundColor:
+ props.backgroundImageColor || 'transparent',
+ }}
+ >
{props.type === 'avatar' ? (
- <Avatar {...commonProps}>{props.emptyText}</Avatar>
+ <Avatar {...commonProps}>{emptyText}</Avatar>
) : (
<Box component={'img'} {...commonProps} />
)}
- </Tooltip>
+ {linkPosition !== 'none' && (
+ <Typography
+ component={Link}
+ variant="caption"
+ onClick={() => setIsDialogOpen(true)}
+ textAlign="center"
+ sx={{ display: 'inline', cursor: 'pointer' }}
+ >
+ Change
+ </Typography>
+ )}
+ </Stack>
<ImageEditorDialog
open={isDialogOpen}
onClose={() => setIsDialogOpen(false)}
{...props}
/>
- </div>
+ </>
);
};
@@ -57,9 +82,13 @@ const ImageEditorDialog = (props: ImageEditorDialogProps) => {
const { setValue, handleSubmit } = useFormContext();
const cropperRef = createRef<ReactCropperElement>();
const initialValue = useFieldValue(props);
- const [imageSrc, setImageSrc] = useState<string | undefined>(initialValue);
+ const [file, setFile] = useState<File | undefined>();
+ const [imageSrc, setImageSrc] = useState<string | undefined>(
+ initialValue?.src
+ );
const onDrop = useCallback((files: File[]) => {
const preview = URL.createObjectURL(files[0]);
+ setFile(files[0]);
setImageSrc(preview);
}, []);
@@ -68,7 +97,15 @@ const ImageEditorDialog = (props: ImageEditorDialogProps) => {
const croppedImage = cropper?.getCroppedCanvas().toDataURL();
if (croppedImage) {
setImageSrc(croppedImage);
- setValue(props.source, croppedImage, { shouldDirty: true });
+ setValue(
+ props.source,
+ {
+ src: croppedImage,
+ title: file?.name,
+ rawFile: file,
+ },
+ { shouldDirty: true }
+ );
props.onClose();
if (props.onSave) {
@@ -77,6 +114,11 @@ const ImageEditorDialog = (props: ImageEditorDialogProps) => {
}
};
+ const deleteImage = () => {
+ setValue(props.source, undefined, { shouldDirty: true });
+ props.onClose();
+ };
+
const { getRootProps, getInputProps } = useDropzone({
accept: { 'image/jpeg': ['.jpeg', '.png'] },
onDrop,
@@ -101,7 +143,7 @@ const ImageEditorDialog = (props: ImageEditorDialogProps) => {
</style>
)}
<DialogCloseButton onClose={props.onClose} />
- <DialogTitle>Resize your image</DialogTitle>
+ <DialogTitle>Upload and resize image</DialogTitle>
<DialogContent>
<Stack gap={2} justifyContent="center">
<Stack
@@ -126,10 +168,15 @@ const ImageEditorDialog = (props: ImageEditorDialogProps) => {
</Stack>
</DialogContent>
<DialogActions sx={{ p: 0 }}>
- <Toolbar sx={{ width: '100%' }}>
+ <Toolbar
+ sx={{ width: '100%', justifyContent: 'space-between' }}
+ >
<Button variant="contained" onClick={updateImage}>
Update Image
</Button>
+ <Button variant="text" color="error" onClick={deleteImage}>
+ Delete
+ </Button>
</Toolbar>
</DialogActions>
</Dialog>
@@ -146,6 +193,8 @@ export interface ImageEditorFieldProps<
height?: number;
type?: 'avatar' | 'image';
onSave?: any;
+ linkPosition?: 'right' | 'bottom' | 'none';
+ backgroundImageColor?: string;
}
export interface ImageEditorDialogProps extends ImageEditorFieldProps {
diff --git a/src/notes/NoteAttachments.tsx b/src/notes/NoteAttachments.tsx
index aeff6422..10ffd4ca 100644
--- a/src/notes/NoteAttachments.tsx
+++ b/src/notes/NoteAttachments.tsx
@@ -1,7 +1,7 @@
import { ImageList, ImageListItem, Stack } from '@mui/material';
import { AttachmentNote, ContactNote, DealNote } from '../types';
import AttachFileIcon from '@mui/icons-material/AttachFile';
-import { supabase } from '../supabase';
+import { FileField } from 'react-admin';
export const NoteAttachments = ({ note }: { note: ContactNote | DealNote }) => {
if (!note.attachments || note.attachments.length === 0) {
@@ -27,7 +27,7 @@ export const NoteAttachments = ({ note }: { note: ContactNote | DealNote }) => {
(attachment: AttachmentNote, index: number) => (
<ImageListItem key={index}>
<img
- src={getPublicUrl(attachment.src)}
+ src={attachment.src}
alt={attachment.title}
style={{
width: '200px',
@@ -51,15 +51,12 @@ export const NoteAttachments = ({ note }: { note: ContactNote | DealNote }) => {
(attachment: AttachmentNote, index: number) => (
<Stack key={index} direction="row" alignItems="center">
<AttachFileIcon fontSize="small" />
-
- <div>
- <a
- href={getPublicUrl(attachment.src)}
- title={attachment.title}
- >
- {attachment.title}
- </a>
- </div>
+ <FileField
+ record={{ attachment }}
+ source="attachment.src"
+ title="attachment.title"
+ target="_blank"
+ />
</Stack>
)
)}
@@ -74,11 +71,3 @@ const isImage = (pathFile: string) => {
}
return ['jpg', 'jpeg', 'png', 'gif', 'svg'].includes(extension);
};
-
-const getPublicUrl = (filePath: string) => {
- const { data } = supabase.storage
- .from('attachments')
- .getPublicUrl(filePath);
-
- return data.publicUrl;
-};
diff --git a/src/settings/SettingsPage.tsx b/src/settings/SettingsPage.tsx
index 3cc9d6d0..a2216474 100644
--- a/src/settings/SettingsPage.tsx
+++ b/src/settings/SettingsPage.tsx
@@ -134,6 +134,7 @@ const SettingsForm = ({
source="avatar"
type="avatar"
onSave={handleAvatarUpdate}
+ linkPosition="right"
/>
<TextRender source="first_name" isEditMode={isEditMode} />
<TextRender source="last_name" isEditMode={isEditMode} />
diff --git a/src/types.ts b/src/types.ts
index dac508d7..2e074c9c 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -26,7 +26,7 @@ export interface Sale extends RaRecord {
first_name: string;
last_name: string;
administrator: boolean;
- avatar?: string;
+ avatar?: RAFile;
user_id: string;
// This is a copy of the user's email, to make it easier to handle by react admin
@@ -36,7 +36,7 @@ export interface Sale extends RaRecord {
export interface Company extends RaRecord {
name: string;
- logo: { title: string; src: string };
+ logo: RAFile;
sector: string;
size: 1 | 10 | 50 | 250 | 500;
linkedin_url: string;
@@ -64,7 +64,7 @@ export interface Contact extends RaRecord {
company_id: Identifier;
company_name: string;
email: string;
- avatar?: string | null;
+ avatar?: Partial<RAFile>;
linkedin_url?: string;
first_seen: string;
last_seen: string;
@@ -170,11 +170,14 @@ export type Activity = RaRecord & { date: string } & (
| ActivityDealNoteCreated
);
-export interface AttachmentNote {
+export interface RAFile {
src: string;
title: string;
+ path?: string;
rawFile: File;
}
+
+export type AttachmentNote = RAFile;
export interface DealStage {
value: string;
label: string;