Skip to content

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

WIP(crm): Backport Contact & Misc

Anthony Rimet7139d345d6ec
diff --git a/package-lock.json b/package-lock.json
index 7b970c55..caaa6d03 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -34,6 +34,7 @@
"@testing-library/jest-dom": "^6.3.0",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
+ "@types/jsonexport": "^3.0.5",
"@types/lodash": "^4.17.7",
"@types/pg": "^8.11.0",
"@types/react": "^18.2.48",
@@ -4405,6 +4406,15 @@
"integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==",
"dev": true
},
+ "node_modules/@types/jsonexport": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/jsonexport/-/jsonexport-3.0.5.tgz",
+ "integrity": "sha512-+zDVaDqNguePOU11YNEsuf/ZRS1ciHeKVYGjfvDFmgG6aCy/s4W4Wy1MiXJIbiyMJLuakGLENCndvmGZpVTV1w==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/lodash": {
"version": "4.17.7",
"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.7.tgz",
diff --git a/package.json b/package.json
index 7542fec2..3befad7a 100644
--- a/package.json
+++ b/package.json
@@ -30,6 +30,7 @@
"@testing-library/jest-dom": "^6.3.0",
"@testing-library/react": "^16.0.0",
"@testing-library/user-event": "^14.5.2",
+ "@types/jsonexport": "^3.0.5",
"@types/lodash": "^4.17.7",
"@types/pg": "^8.11.0",
"@types/react": "^18.2.48",
diff --git a/src/contacts/ContactAside.tsx b/src/contacts/ContactAside.tsx
index 7ef50138..88260b26 100644
--- a/src/contacts/ContactAside.tsx
+++ b/src/contacts/ContactAside.tsx
@@ -1,9 +1,10 @@
import EmailIcon from '@mui/icons-material/Email';
import LinkedInIcon from '@mui/icons-material/LinkedIn';
import PhoneIcon from '@mui/icons-material/Phone';
-import { Box, Divider, Stack, Typography } from '@mui/material';
+import { Box, Divider, Stack, SvgIcon, Typography } from '@mui/material';
import {
DateField,
+ DeleteButton,
EditButton,
EmailField,
FunctionField,
@@ -19,10 +20,12 @@ import { AddTask } from '../tasks/AddTask';
import { TasksIterator } from '../tasks/TasksIterator';
import { TagsListEdit } from './TagsListEdit';
+import { useLocation } from 'react-router';
import { useConfigurationContext } from '../root/ConfigurationContext';
import { Contact, Sale } from '../types';
export const ContactAside = ({ link = 'edit' }: { link?: 'edit' | 'show' }) => {
+ const location = useLocation();
const { contactGender } = useConfigurationContext();
const record = useRecordContext<Contact>();
if (!record) return null;
@@ -48,6 +51,11 @@ export const ContactAside = ({ link = 'edit' }: { link?: 'edit' | 'show' }) => {
<EmailField source="email" />
</Stack>
)}
+ {record.has_newsletter && (
+ <Typography variant="body2" color="textSecondary" pl={3.5}>
+ Subscribed to newsletter
+ </Typography>
+ )}
{record.linkedin_url && (
<Stack
@@ -59,14 +67,13 @@ export const ContactAside = ({ link = 'edit' }: { link?: 'edit' | 'show' }) => {
<LinkedInIcon color="disabled" fontSize="small" />
<UrlField
source="linkedin_url"
- content="linkedin_url"
+ content="LinkedIn profile"
target="_blank"
rel="noopener"
- label="LinkedIn"
/>
</Stack>
)}
- {record.phone_number1.number && (
+ {record.phone_number1?.number && (
<Stack direction="row" alignItems="center" gap={1}>
<PhoneIcon color="disabled" fontSize="small" />
<Box>
@@ -80,8 +87,13 @@ export const ContactAside = ({ link = 'edit' }: { link?: 'edit' | 'show' }) => {
</Box>
</Stack>
)}
- {record.phone_number2.number && (
- <Stack direction="row" alignItems="center" gap={1}>
+ {record.phone_number2?.number && (
+ <Stack
+ direction="row"
+ alignItems="center"
+ gap={1}
+ minHeight={24}
+ >
<PhoneIcon color="disabled" fontSize="small" />
<Box>
<TextField source="phone_number2.number" />{' '}
@@ -97,7 +109,21 @@ export const ContactAside = ({ link = 'edit' }: { link?: 'edit' | 'show' }) => {
<SelectField
source="gender"
choices={contactGender}
- optionText="label"
+ optionText={choice => (
+ <Stack
+ direction="row"
+ alignItems="center"
+ gap={1}
+ minHeight={24}
+ >
+ <SvgIcon
+ component={choice.icon}
+ color="disabled"
+ fontSize="small"
+ ></SvgIcon>
+ <span>{choice.label}</span>
+ </Stack>
+ )}
optionValue="value"
/>
<Typography variant="subtitle2" mt={2}>
@@ -155,7 +181,7 @@ export const ContactAside = ({ link = 'edit' }: { link?: 'edit' | 'show' }) => {
<Divider />
<TagsListEdit />
</Box>
- <Box>
+ <Box mb={3}>
<Typography variant="subtitle2">Tasks</Typography>
<Divider />
<ReferenceManyField
@@ -167,6 +193,7 @@ export const ContactAside = ({ link = 'edit' }: { link?: 'edit' | 'show' }) => {
</ReferenceManyField>
<AddTask />
</Box>
+ <DeleteButton redirect={location.state?.from || undefined} />
</Box>
);
};
diff --git a/src/contacts/ContactEdit.tsx b/src/contacts/ContactEdit.tsx
index d906d325..0cd9ec52 100644
--- a/src/contacts/ContactEdit.tsx
+++ b/src/contacts/ContactEdit.tsx
@@ -1,5 +1,11 @@
import * as React from 'react';
-import { EditBase, Form, Toolbar, useEditContext } from 'react-admin';
+import {
+ EditBase,
+ Form,
+ SaveButton,
+ Toolbar,
+ useEditContext,
+} from 'react-admin';
import { Card, CardContent, Box } from '@mui/material';
import { ContactInputs } from './ContactInputs';
@@ -23,7 +29,9 @@ const ContactEditContent = () => {
<CardContent>
<ContactInputs />
</CardContent>
- <Toolbar />
+ <Toolbar>
+ <SaveButton />
+ </Toolbar>
</Card>
</Form>
</Box>
diff --git a/src/contacts/ContactEmpty.tsx b/src/contacts/ContactEmpty.tsx
index 507a41f9..67408029 100644
--- a/src/contacts/ContactEmpty.tsx
+++ b/src/contacts/ContactEmpty.tsx
@@ -25,7 +25,7 @@ export const ContactEmpty = () => {
color="text.secondary"
gutterBottom
>
- It looks like your contact list is empty.
+ It seems your contact list is empty.
</Typography>
</Stack>
<Stack spacing={2} direction="row">
diff --git a/src/contacts/ContactImportButton.tsx b/src/contacts/ContactImportButton.tsx
index aed8c462..38f28fc8 100644
--- a/src/contacts/ContactImportButton.tsx
+++ b/src/contacts/ContactImportButton.tsx
@@ -1,152 +1,17 @@
import UploadIcon from '@mui/icons-material/Upload';
-import { Box, CircularProgress, Stack } from '@mui/material';
-import Alert from '@mui/material/Alert';
-import Dialog from '@mui/material/Dialog';
-import DialogActions from '@mui/material/DialogActions';
-import DialogContent from '@mui/material/DialogContent';
-import DialogTitle from '@mui/material/DialogTitle';
-import * as Papa from 'papaparse';
import { useState } from 'react';
-import {
- Button,
- FileField,
- FileInput,
- Form,
- Toolbar,
- useDataProvider,
- useGetIdentity,
- useNotify,
- useRefresh,
-} from 'react-admin';
-import { Link } from 'react-router-dom';
-import * as sampleCsv from './contacts_export.csv?raw';
-import { ContentImportSchema, useContactImport } from './useContactImport';
-import { DialogCloseButton } from '../misc/DialogCloseButton';
-
-const SAMPLE_URL = `data:text/csv;charset=utf-8,${encodeURIComponent(sampleCsv.default)}`;
+import { Button } from 'react-admin';
+import { ContactImportModal } from './ContactImportModal';
export const ContactImportButton = () => {
- const refresh = useRefresh();
- const user = useGetIdentity();
- const dataProvider = useDataProvider();
- const notify = useNotify();
- const contactImports = useContactImport();
-
- const [file, setFile] = useState<File | null>(null);
-
- const [importState, setImportState] = useState<
- 'hidden' | 'idle' | 'running' | 'error' | 'complete'
- >('hidden');
-
- const [errorCount, setErrorCount] = useState(0);
- const [importCount, setImportCount] = useState(0);
+ const [modalOpen, setModalOpen] = useState(false);
const handleOpenModal = () => {
- setImportState('idle');
- setErrorCount(0);
- setImportCount(0);
- };
-
- const handleCancel = () => {
- setImportState('hidden');
- };
-
- const handleFileChange = (file: File | null) => {
- setFile(file);
+ setModalOpen(true);
};
- const startImport = async () => {
- if (!file) {
- return;
- }
-
- setImportState('running');
-
- Papa.parse<ContentImportSchema>(file, {
- header: true,
- skipEmptyLines: true,
- async step(row, parser) {
- // We pause the parser to avoid processing the next row until the current one is done
- // Otherwise completed will be called before the last row is processed
- parser.pause();
-
- try {
- if (row.errors.length > 0) {
- throw row.errors[0];
- }
-
- const tagNames = (row.data.tags ?? '')
- .split(',')
- .map((tag: string) => tag.trim())
- .filter((tag: string) => tag);
-
- const company = await contactImports.getCompany(
- row.data.company
- );
- const tags = await contactImports.getTags(tagNames);
-
- const {
- first_name,
- last_name,
- gender,
- title,
- email,
- phone_number1,
- phone_number2,
- background,
- acquisition,
- first_seen,
- last_seen,
- has_newsletter,
- status,
- } = row.data;
-
- await dataProvider.create('contacts', {
- data: {
- first_name,
- last_name,
- gender,
- title,
- email,
- phone_number1,
- phone_number2,
- background,
- acquisition,
- first_seen: new Date(first_seen),
- last_seen: new Date(last_seen),
- has_newsletter:
- has_newsletter.toLowerCase() === 'true',
- status,
- company_id: company.id,
- tags: tags.map(tag => tag.id),
- sales_id: user?.identity?.id,
- },
- });
- setImportCount(importCount => importCount + 1);
- } catch (error) {
- console.error('Failed to import row', error);
- setErrorCount(errorCount => errorCount + 1);
- } finally {
- // We resume the parser to process the next row
- setTimeout(() => parser.resume(), 0);
- }
- },
- error: error => {
- console.error(
- 'An error occurred while importing the file',
- error
- );
-
- setImportState('error');
- notify('An error occurred while importing the file', {
- type: 'error',
- });
- },
- complete: async () => {
- setImportState('complete');
- refresh();
- },
- });
+ const handleCloseModal = () => {
+ setModalOpen(false);
};
return (
@@ -157,120 +22,7 @@ export const ContactImportButton = () => {
onClick={handleOpenModal}
/>
- <Dialog open={importState !== 'hidden'} maxWidth="lg" fullWidth>
- <DialogCloseButton onClose={handleCancel} />
- <DialogTitle>Import</DialogTitle>
- <DialogContent>
- <Form>
- <Stack spacing={2}>
- {importState === 'running' && (
- <Alert
- severity="info"
- variant="outlined"
- action={
- <Box
- sx={{
- display: 'flex',
- height: '100%',
- alignItems: 'center',
- }}
- >
- <CircularProgress size={20} />
- </Box>
- }
- >
- Import is running, please do not close this
- tab
- </Alert>
- )}
-
- {importState === 'complete' && (
- <Alert severity="success" variant="outlined">
- Contacts import complete
- </Alert>
- )}
-
- {importState === 'error' && (
- <Alert severity="error" variant="outlined">
- Failed to import this file, please make sure
- your provided a valid CSV file
- </Alert>
- )}
- {importState === 'idle' ? (
- <>
- <Alert
- severity="info"
- action={
- <Button
- component={Link}
- label="Download CSV sample"
- color="info"
- to={SAMPLE_URL}
- />
- }
- >
- Here is a sample CSV file you can use as
- a template
- </Alert>
-
- <FileInput
- source="csv"
- label="CSV File"
- accept={{ 'text/csv': ['.csv'] }}
- onChange={handleFileChange}
- >
- <FileField source="src" title="title" />
- </FileInput>
- </>
- ) : (
- <>
- <Alert severity="success">
- Imported {importCount} contacts
- </Alert>
- {errorCount > 0 && (
- <Alert severity="error">
- Encountered {errorCount} errors
- </Alert>
- )}
- </>
- )}
- </Stack>
- </Form>
- </DialogContent>
- <DialogActions
- sx={{
- p: 0,
- justifyContent: 'flex-start',
- }}
- >
- <Toolbar
- sx={{
- width: '100%',
- }}
- >
- {importState === 'idle' ? (
- <>
- <Button
- label="Import"
- variant="contained"
- onClick={startImport}
- disabled={!file || importState !== 'idle'}
- />
- </>
- ) : (
- <Button
- label="Close"
- onClick={handleCancel}
- disabled={importState === 'running'}
- />
- )}
- </Toolbar>
- </DialogActions>
- </Dialog>
+ <ContactImportModal open={modalOpen} onClose={handleCloseModal} />
</>
);
};
-
-export function toDataUrl(content: string, mimeType: string) {
- return `data:${mimeType},${encodeURIComponent(content)}`;
-}
diff --git a/src/contacts/ContactImportModal.tsx b/src/contacts/ContactImportModal.tsx
new file mode 100644
index 00000000..0fc56a60
--- /dev/null
+++ b/src/contacts/ContactImportModal.tsx
@@ -0,0 +1,218 @@
+import { Box, CircularProgress, Stack, Typography } from '@mui/material';
+import Alert from '@mui/material/Alert';
+import Dialog from '@mui/material/Dialog';
+import DialogActions from '@mui/material/DialogActions';
+import DialogContent from '@mui/material/DialogContent';
+import DialogTitle from '@mui/material/DialogTitle';
+import MuiLink from '@mui/material/Link';
+import {
+ Button,
+ FileField,
+ FileInput,
+ Form,
+ Toolbar,
+ useRefresh,
+} from 'react-admin';
+import { Link } from 'react-router-dom';
+import { DialogCloseButton } from '../misc/DialogCloseButton';
+import { usePapaParse } from '../misc/usePapaParse';
+import { ContactImportSchema, useContactImport } from './useContactImport';
+
+import { MouseEvent, useEffect, useState } from 'react';
+import * as sampleCsv from './contacts_export.csv?raw';
+
+const SAMPLE_URL = `data:text/csv;name=crm_contacts_sample.csv;charset=utf-8,${encodeURIComponent(sampleCsv.default)}`;
+
+type ContactImportModalProps = {
+ open: boolean;
+ onClose(): void;
+};
+
+export function ContactImportModal({ open, onClose }: ContactImportModalProps) {
+ const refresh = useRefresh();
+ const { processBatch } = useContactImport();
+ const { importer, parseCsv, reset } = usePapaParse<ContactImportSchema>({
+ batchSize: 10,
+ processBatch,
+ });
+
+ const [file, setFile] = useState<File | null>(null);
+
+ useEffect(() => {
+ if (importer.state === 'complete') {
+ refresh();
+ }
+ }, [importer.state, refresh]);
+
+ const handleFileChange = (file: File | null) => {
+ setFile(file);
+ };
+
+ const startImport = async () => {
+ if (!file) {
+ return;
+ }
+
+ parseCsv(file);
+ };
+
+ const handleClose = () => {
+ reset();
+ onClose();
+ };
+
+ const handleReset = (e: MouseEvent<HTMLAnchorElement>) => {
+ e.preventDefault();
+ reset();
+ };
+
+ return (
+ <Dialog open={open} maxWidth="md" fullWidth>
+ <DialogCloseButton onClose={handleClose} />
+ <DialogTitle>Import</DialogTitle>
+ <DialogContent>
+ <Form>
+ <Stack spacing={2}>
+ {importer.state === 'running' && (
+ <Stack gap={2}>
+ <Alert
+ severity="info"
+ action={
+ <Box
+ sx={{
+ display: 'flex',
+ height: '100%',
+ alignItems: 'center',
+ padding: '0',
+ }}
+ >
+ <CircularProgress size={20} />
+ </Box>
+ }
+ sx={{
+ alignItems: 'center',
+ '& .MuiAlert-action': {
+ padding: 0,
+ marginRight: 0,
+ },
+ }}
+ >
+ The import is running, please do not close
+ this tab.
+ </Alert>
+ <Typography variant="body2">
+ Imported{' '}
+ <strong>
+ {importer.importCount} /{' '}
+ {importer.rowCount}
+ </strong>{' '}
+ contacts, with{' '}
+ <strong>{importer.errorCount}</strong>{' '}
+ errors.
+ {importer.remainingTime !== null && (
+ <>
+ {' '}
+ Estimated remaining time:{' '}
+ <strong>
+ {millisecondsToTime(
+ importer.remainingTime
+ )}
+ </strong>
+ .{' '}
+ <MuiLink
+ href="#"
+ onClick={handleReset}
+ color="error"
+ >
+ Stop import
+ </MuiLink>
+ </>
+ )}
+ </Typography>
+ </Stack>
+ )}
+
+ {importer.state === 'error' && (
+ <Alert severity="error">
+ Failed to import this file, please make sure
+ your provided a valid CSV file.
+ </Alert>
+ )}
+
+ {importer.state === 'complete' && (
+ <Alert severity="success">
+ Contacts import complete. Imported{' '}
+ {importer.importCount} contacts, with{' '}
+ {importer.errorCount} errors
+ </Alert>
+ )}
+
+ {importer.state === 'idle' && (
+ <>
+ <Alert
+ severity="info"
+ action={
+ <Button
+ component={Link}
+ label="Download CSV sample"
+ color="info"
+ to={SAMPLE_URL}
+ />
+ }
+ >
+ Here is a sample CSV file you can use as a
+ template
+ </Alert>
+
+ <FileInput
+ source="csv"
+ label="CSV File"
+ accept={{ 'text/csv': ['.csv'] }}
+ onChange={handleFileChange}
+ >
+ <FileField source="src" title="title" />
+ </FileInput>
+ </>
+ )}
+ </Stack>
+ </Form>
+ </DialogContent>
+ <DialogActions
+ sx={{
+ p: 0,
+ justifyContent: 'flex-start',
+ }}
+ >
+ <Toolbar
+ sx={{
+ width: '100%',
+ }}
+ >
+ {importer.state === 'idle' ? (
+ <>
+ <Button
+ label="Import"
+ variant="contained"
+ onClick={startImport}
+ disabled={!file}
+ />
+ </>
+ ) : (
+ <Button
+ label="Close"
+ onClick={handleClose}
+ disabled={importer.state === 'running'}
+ />
+ )}
+ </Toolbar>
+ </DialogActions>
+ </Dialog>
+ );
+}
+
+function millisecondsToTime(ms: number) {
+ var seconds = Math.floor((ms / 1000) % 60);
+ var minutes = Math.floor((ms / (60 * 1000)) % 60);
+
+ return `${minutes}m ${seconds}s`;
+}
diff --git a/src/contacts/ContactInputs.tsx b/src/contacts/ContactInputs.tsx
index 534d5f21..a56eca2a 100644
--- a/src/contacts/ContactInputs.tsx
+++ b/src/contacts/ContactInputs.tsx
@@ -28,26 +28,21 @@ export const ContactInputs = () => {
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
return (
- <Stack gap={4} p={1}>
- <Stack gap={2}>
- <Avatar />
- <Stack gap={4} flexDirection={isMobile ? 'column' : 'row'}>
+ <Stack gap={2} p={1}>
+ <Avatar />
+ <Stack gap={4} direction={isMobile ? 'column' : 'row'}>
+ <Stack gap={4} flex={1}>
<ContactIdentityInputs />
- <Divider
- orientation={isMobile ? 'horizontal' : 'vertical'}
- flexItem
- />
<ContactPositionInputs />
</Stack>
- </Stack>
-
- <Stack gap={4} flexDirection={isMobile ? 'column' : 'row'}>
- <ContactPersonalInformationInputs />
<Divider
orientation={isMobile ? 'horizontal' : 'vertical'}
flexItem
/>
- <ContactMiscInputs />
+ <Stack gap={4} flex={1}>
+ <ContactPersonalInformationInputs />
+ <ContactMiscInputs />
+ </Stack>
</Stack>
</Stack>
);
@@ -56,7 +51,7 @@ export const ContactInputs = () => {
const ContactIdentityInputs = () => {
const { contactGender } = useConfigurationContext();
return (
- <Stack gap={1} flex={1}>
+ <Stack>
<Typography variant="h6">Identity</Typography>
<RadioButtonGroupInput
label={false}
@@ -108,7 +103,7 @@ const ContactPositionInputs = () => {
}
};
return (
- <Stack gap={1} flex={1}>
+ <Stack>
<Typography variant="h6">Position</Typography>
<TextInput source="title" helperText={false} />
<ReferenceInput source="company_id" reference="companies">
@@ -125,7 +120,7 @@ const ContactPositionInputs = () => {
const ContactPersonalInformationInputs = () => {
return (
- <Stack gap={1} flex={1}>
+ <Stack>
<Typography variant="h6">Personal info</Typography>
<TextInput source="email" helperText={false} validate={email()} />
<Stack gap={1} flexDirection="row">
@@ -170,7 +165,7 @@ const ContactPersonalInformationInputs = () => {
const ContactMiscInputs = () => {
return (
- <Stack gap={1} flex={1}>
+ <Stack>
<Typography variant="h6">Misc</Typography>
<TextInput
source="background"
@@ -183,6 +178,9 @@ const ContactMiscInputs = () => {
reference="sales"
source="sales_id"
sort={{ field: 'last_name', order: 'ASC' }}
+ filter={{
+ disabled_neq: true,
+ }}
>
<SelectInput
helperText={false}
diff --git a/src/contacts/ContactList.tsx b/src/contacts/ContactList.tsx
index 93a529da..e3463669 100644
--- a/src/contacts/ContactList.tsx
+++ b/src/contacts/ContactList.tsx
@@ -3,6 +3,8 @@ import { Card, LinearProgress, Stack } from '@mui/material';
import jsonExport from 'jsonexport/dist';
import type { Exporter } from 'react-admin';
import {
+ BulkActionsToolbar,
+ BulkDeleteButton,
CreateButton,
downloadCSV,
ExportButton,
@@ -60,6 +62,9 @@ const ContactListLayout = () => {
<Stack sx={{ width: '100%' }}>
<Title title={'Contacts'} />
<ListToolbar actions={<ContactListActions />} />
+ <BulkActionsToolbar>
+ <BulkDeleteButton />
+ </BulkActionsToolbar>
<Card>
<ContactListContent />
</Card>
diff --git a/src/contacts/ContactListContent.tsx b/src/contacts/ContactListContent.tsx
index cb8ce6ba..edc8798d 100644
--- a/src/contacts/ContactListContent.tsx
+++ b/src/contacts/ContactListContent.tsx
@@ -1,8 +1,6 @@
/* eslint-disable import/no-anonymous-default-export */
import * as React from 'react';
import {
- BulkActionsToolbar,
- BulkDeleteButton,
RecordContextProvider,
ReferenceField,
SimpleListLoading,
@@ -22,7 +20,7 @@ import {
} from '@mui/material';
import type { Theme } from '@mui/material';
import { Link } from 'react-router-dom';
-import { formatDistance } from 'date-fns';
+import { formatRelative } from 'date-fns';
import { Avatar } from './Avatar';
import { Status } from '../misc/Status';
@@ -50,9 +48,6 @@ export const ContactListContent = () => {
return (
<>
- <BulkActionsToolbar>
- <BulkDeleteButton />
- </BulkActionsToolbar>
<List dense>
{contacts.map(contact => (
<RecordContextProvider key={contact.id} value={contact}>
@@ -112,10 +107,11 @@ export const ContactListContent = () => {
title={contact.last_seen}
>
{!isSmall && 'last activity '}
- {formatDistance(
+ {formatRelative(
contact.last_seen,
now
- )} ago <Status status={contact.status} />
+ )}{' '}
+ <Status status={contact.status} />
</Typography>
</ListItemSecondaryAction>
</ListItem>
diff --git a/src/contacts/TagsList.tsx b/src/contacts/TagsList.tsx
index 8425bd24..e3fb5901 100644
--- a/src/contacts/TagsList.tsx
+++ b/src/contacts/TagsList.tsx
@@ -26,7 +26,7 @@ export const TagsList = () => (
source="tags"
reference="tags"
>
- <SingleFieldList linkType={false}>
+ <SingleFieldList linkType={false} component="span">
<ColoredChipField source="name" variant="outlined" size="small" />
</SingleFieldList>
</ReferenceArrayField>
diff --git a/src/contacts/contacts_export.csv b/src/contacts/contacts_export.csv
index 6ac7e587..8000d62d 100644
--- a/src/contacts/contacts_export.csv
+++ b/src/contacts/contacts_export.csv
@@ -1,2 +1,2 @@
-first_name,last_name,gender,title,company,email,phone_number1,phone_number2,background,acquisition,first_seen,last_seen,has_newsletter,status,tags
-John,DOE,male,Developer,Marmelab,[email protected],659-980-2015,740.645.3807,,outbound,2024-07-01,2024-07-01T11:54:49.950Z,FALSE,in-contract,"influencer, developer"
\ No newline at end of file
+first_name,last_name,gender,title,company,email,phone_number1.number,phone_number1.type,phone_number2.number,phone_number2.type,background,acquisition,first_seen,last_seen,has_newsletter,status,tags
+John,DOE,male,Developer,Marmelab,[email protected],659-980-2015,work,740.645.3807,home,,outbound,2024-07-01,2024-07-01T11:54:49.950Z,FALSE,in-contract,"influencer, developer"
\ No newline at end of file
diff --git a/src/contacts/useContactImport.tsx b/src/contacts/useContactImport.tsx
index 6cee0be5..ae908afd 100644
--- a/src/contacts/useContactImport.tsx
+++ b/src/contacts/useContactImport.tsx
@@ -2,15 +2,17 @@ import { useCallback, useMemo } from 'react';
import { useDataProvider, useGetIdentity } from 'react-admin';
import { Company, Tag } from '../types';
-export type ContentImportSchema = {
+export type ContactImportSchema = {
first_name: string;
last_name: string;
gender: string;
title: string;
company: string;
email: string;
- phone_number1: string;
- phone_number2: string;
+ 'phone_number1.number': string;
+ 'phone_number1.type': string;
+ 'phone_number2.number': string;
+ 'phone_number2.type': string;
background: string;
acquisition: string;
avatar: string;
@@ -33,35 +35,67 @@ export function useContactImport() {
[dataProvider]
);
- const getCompany = useCallback(
- async (name: string) => {
- const trimmedName = name.trim();
- if (companiesCache.has(trimmedName)) {
- return companiesCache.get(trimmedName);
- }
+ const _cacheFetchBatch = useCallback(
+ async function <T>(
+ entity: string,
+ cache: Map<string, T>,
+ names: string[],
+ getCreateData: (name: string) => Partial<T>
+ ) {
+ const trimmedNames = [...new Set(names.map(name => name.trim()))];
+ const uncachedEntities = trimmedNames.filter(
+ name => !cache.has(name)
+ );
- const companies = await dataProvider.getList('companies', {
- filter: { name: trimmedName },
- pagination: { page: 1, perPage: 1 },
- sort: { field: 'first_name', order: 'ASC' },
- });
+ const entities = uncachedEntities.length
+ ? await dataProvider.getList(entity, {
+ filter: { name: uncachedEntities },
+ pagination: { page: 1, perPage: 1 },
+ sort: { field: 'first_name', order: 'ASC' },
+ })
+ : { data: [] };
- if (companies.data.length === 1) {
- companiesCache.set(trimmedName, companies.data[0]);
- return companies.data[0];
+ for (const entity of entities.data) {
+ cache.set(entity.name.trim(), entity);
}
- const createdCompany = await dataProvider.create('companies', {
- data: {
- name: trimmedName,
- created_at: new Date(),
+ await Promise.all(
+ uncachedEntities.map(async name => {
+ if (!cache.has(name)) {
+ const createdEntity = await dataProvider.create(
+ entity,
+ {
+ data: getCreateData(name),
+ }
+ );
+ cache.set(name, createdEntity.data);
+ }
+ return Promise.resolve();
+ })
+ );
+
+ return trimmedNames.reduce((acc, name) => {
+ acc.set(name, cache.get(name) as T);
+ return acc;
+ }, new Map<string, T>());
+ },
+ [dataProvider]
+ );
+
+ const getCompanies = useCallback(
+ async (names: string[]) => {
+ return _cacheFetchBatch<Company>(
+ 'companies',
+ companiesCache,
+ names,
+ name => ({
+ name,
+ created_at: new Date().toISOString(),
sales_id: user?.identity?.id,
- },
- });
- companiesCache.set(trimmedName, createdCompany.data);
- return createdCompany.data;
+ })
+ );
},
- [dataProvider, companiesCache, user?.identity?.id]
+ [_cacheFetchBatch, companiesCache, user?.identity?.id]
);
// Tags cache to avoid creating the same tag multiple times and costly roundtrips
@@ -70,39 +104,97 @@ export function useContactImport() {
const tagsCache = useMemo(() => new Map<string, Tag>(), [dataProvider]);
const getTags = useCallback(
- async (tagNames: string[]) => {
- const missingTagNames = tagNames.filter(
- tagName => !tagsCache.has(tagName)
- );
+ async (names: string[]) => {
+ return _cacheFetchBatch<Tag>('tags', tagsCache, names, name => ({
+ name,
+ color: '#f9f9f9',
+ }));
+ },
+ [_cacheFetchBatch, tagsCache]
+ );
- const uncachedTags = await dataProvider.getList('tags', {
- filter: { name: missingTagNames },
- pagination: { page: 1, perPage: missingTagNames.length },
- sort: { field: 'name', order: 'ASC' },
- });
+ const parseTags = useCallback((tags: string) => {
+ return (
+ tags
+ ?.split(',')
+ ?.map((tag: string) => tag.trim())
+ ?.filter((tag: string) => tag) ?? []
+ );
+ }, []);
- for (const tag of uncachedTags.data) {
- tagsCache.set(tag.name, tag);
- }
+ const processBatch = useCallback(
+ async (batch: ContactImportSchema[]) => {
+ const [companies, tags] = await Promise.all([
+ getCompanies(batch.map(contact => contact.company.trim())),
+ getTags(batch.flatMap(batch => parseTags(batch.tags))),
+ ]);
- for await (const tagName of missingTagNames) {
- if (!tagsCache.has(tagName)) {
- const createdTag = await dataProvider.create('tags', {
- data: { name: tagName, color: '#f9f9f9' },
- });
- tagsCache.set(tagName, createdTag.data);
- }
- }
+ await Promise.all(
+ batch.map(
+ async ({
+ first_name,
+ last_name,
+ gender,
+ title,
+ email,
+ 'phone_number1.type': phoneNumber1Type,
+ 'phone_number1.number': phoneNumber1Number,
+ 'phone_number2.type': phoneNumber2Type,
+ 'phone_number2.number': phoneNumber2Number,
+ background,
+ acquisition,
+ first_seen,
+ last_seen,
+ has_newsletter,
+ status,
+ company: companyName,
+ tags: tagNames,
+ }) => {
+ const company = companies.get(companyName.trim());
+ const tagList = parseTags(tagNames)
+ .map(name => tags.get(name))
+ .filter((tag): tag is Tag => !!tag);
- return tagNames
- .map(tagName => tagsCache.get(tagName))
- .filter((tag): tag is Tag => tag != null);
+ // This should not happen, but we silently fail in case of error
+ // TODO: warn user about missing company
+ if (!company) {
+ return;
+ }
+
+ return dataProvider.create('contacts', {
+ data: {
+ first_name,
+ last_name,
+ gender,
+ title,
+ email,
+ phone_number1: {
+ number: phoneNumber1Number,
+ type: phoneNumber1Type,
+ },
+ phone_number2: {
+ number: phoneNumber2Number,
+ type: phoneNumber2Type,
+ },
+ background,
+ acquisition,
+ first_seen: new Date(first_seen),
+ last_seen: new Date(last_seen),
+ has_newsletter,
+ status,
+ company_id: company.id,
+ tags: tagList.map(tag => tag.id),
+ sales_id: user?.identity?.id,
+ },
+ });
+ }
+ )
+ );
},
- [dataProvider, tagsCache]
+ [dataProvider, getCompanies, parseTags, getTags, user?.identity?.id]
);
return {
- getTags,
- getCompany,
+ processBatch,
};
}
diff --git a/src/dashboard/Dashboard.tsx b/src/dashboard/Dashboard.tsx
index ea828779..eb0dc880 100644
--- a/src/dashboard/Dashboard.tsx
+++ b/src/dashboard/Dashboard.tsx
@@ -1,29 +1,67 @@
-import { Grid } from '@mui/material';
+import { Grid, Stack } from '@mui/material';
import { DashboardActivityLog } from './DashboardActivityLog';
import { DealsChart } from './DealsChart';
import { HotContacts } from './HotContacts';
import { TasksList } from './TasksList';
import { Welcome } from './Welcome';
+import { useGetList } from 'react-admin';
+import { Contact, ContactNote } from '../types';
+import { DashboardStepper } from './DashboardStepper';
-export const Dashboard = () => (
- <Grid container spacing={2} mt={1}>
- <Grid container item xs={12} md={9} spacing={2}>
- <Grid item xs={12} md={4}>
- <Welcome />
- </Grid>
- <Grid item xs={12} md={8}>
- <DealsChart />
- </Grid>
- <Grid item xs={12} md={4}>
- <HotContacts />
+export const Dashboard = () => {
+ const {
+ data: dataContact,
+ total: totalContact,
+ isPending: isPendingContact,
+ } = useGetList<Contact>('contacts', {
+ pagination: { page: 1, perPage: 1 },
+ });
+
+ const { total: totalContactNotes, isPending: isPendingContactNotes } =
+ useGetList<ContactNote>('contactNotes', {
+ pagination: { page: 1, perPage: 1 },
+ });
+
+ const { total: totalDeal, isPending: isPendingDeal } = useGetList<Contact>(
+ 'deals',
+ {
+ pagination: { page: 1, perPage: 1 },
+ }
+ );
+
+ const isPending =
+ isPendingContact || isPendingContactNotes || isPendingDeal;
+
+ if (isPending) {
+ return null;
+ }
+
+ if (!totalContact) {
+ return <DashboardStepper step={1} />;
+ }
+
+ if (!totalContactNotes) {
+ return <DashboardStepper step={2} contactId={dataContact?.[0]?.id} />;
+ }
+
+ return (
+ <Grid container spacing={2} mt={1} rowGap={4}>
+ <Grid item xs={12} md={3}>
+ <Stack gap={4}>
+ <Welcome />
+ <HotContacts />
+ </Stack>
</Grid>
- <Grid item xs={12} md={8}>
- <DashboardActivityLog />
+ <Grid item xs={12} md={6}>
+ <Stack gap={4}>
+ {totalDeal ? <DealsChart /> : null}
+ <DashboardActivityLog />
+ </Stack>
</Grid>
- </Grid>
- <Grid item xs={12} md={3}>
- <TasksList />
+ <Grid item xs={12} md={3}>
+ <TasksList />
+ </Grid>
</Grid>
- </Grid>
-);
+ );
+};
diff --git a/src/dashboard/DashboardStepper.tsx b/src/dashboard/DashboardStepper.tsx
new file mode 100644
index 00000000..11177adf
--- /dev/null
+++ b/src/dashboard/DashboardStepper.tsx
@@ -0,0 +1,129 @@
+import {
+ Box,
+ Card,
+ CardContent,
+ LinearProgress,
+ Stack,
+ Typography,
+ Button,
+} from '@mui/material';
+import useAppBarHeight from '../misc/useAppBarHeight';
+import CheckCircleIcon from '@mui/icons-material/CheckCircle';
+import RadioButtonUncheckedOutlinedIcon from '@mui/icons-material/RadioButtonUncheckedOutlined';
+import { CreateButton, Identifier } from 'react-admin';
+import { ContactImportButton } from '../contacts/ContactImportButton';
+import { Link } from 'react-router-dom';
+
+export const DashboardStepper = ({
+ step,
+ contactId,
+}: {
+ step: number;
+ contactId?: Identifier;
+}) => {
+ const appbarHeight = useAppBarHeight();
+ return (
+ <Stack
+ justifyContent="center"
+ alignItems="center"
+ sx={{
+ height: `calc(100dvh - ${appbarHeight}px)`,
+ }}
+ >
+ <Card
+ sx={{
+ width: '100%',
+ maxWidth: '600px',
+ }}
+ >
+ <CardContent>
+ <Stack
+ direction="row"
+ alignItems="center"
+ justifyContent="space-between"
+ mb={2}
+ >
+ <Typography variant="h6" fontWeight="bold">
+ What's next?
+ </Typography>
+ <Box sx={{ width: '150px' }}>
+ <LinearProgress
+ variant="determinate"
+ value={(step / 3) * 100}
+ color="success"
+ />
+ <Typography variant="body2" align="right">
+ {step}/3 done
+ </Typography>
+ </Box>
+ </Stack>
+ <Stack gap={3}>
+ <Stack gap={2} direction="row">
+ <CheckCircleIcon color="success" fontSize="small" />
+ <Typography variant="body2" fontWeight="bold">
+ Install Atomic CRM
+ </Typography>
+ </Stack>
+ <Stack gap={2} direction="row">
+ {step > 1 ? (
+ <CheckCircleIcon
+ color="success"
+ fontSize="small"
+ />
+ ) : (
+ <RadioButtonUncheckedOutlinedIcon
+ color="disabled"
+ fontSize="small"
+ />
+ )}
+
+ <Stack gap={1}>
+ <Typography variant="body2" fontWeight="bold">
+ Add your first contact
+ </Typography>
+ <Typography variant="caption">
+ Create or import your contacts
+ </Typography>
+ <Stack spacing={2} direction="row">
+ <CreateButton
+ variant="contained"
+ label="New Contact"
+ resource="contacts"
+ size="small"
+ />
+ <ContactImportButton />
+ </Stack>
+ </Stack>
+ </Stack>
+ <Stack gap={2} direction="row">
+ <RadioButtonUncheckedOutlinedIcon
+ fontSize="small"
+ color="disabled"
+ />
+ <Stack gap={1}>
+ <Typography variant="body2" fontWeight="bold">
+ Add your first note
+ </Typography>
+ <Typography variant="caption">
+ Got to a contact page and add a note
+ </Typography>
+ <Button
+ component={Link}
+ variant="contained"
+ size="small"
+ disabled={step < 2}
+ sx={{
+ width: '100px',
+ }}
+ to={`/contacts/${contactId}/show`}
+ >
+ Add note
+ </Button>
+ </Stack>
+ </Stack>
+ </Stack>
+ </CardContent>
+ </Card>
+ </Stack>
+ );
+};
diff --git a/src/misc/ContactOption.tsx b/src/misc/ContactOption.tsx
new file mode 100644
index 00000000..ea811b79
--- /dev/null
+++ b/src/misc/ContactOption.tsx
@@ -0,0 +1,25 @@
+import { Stack, Typography } from '@mui/material';
+import { useRecordContext } from 'react-admin';
+import { Avatar } from '../contacts/Avatar';
+import { Contact } from '../types';
+
+const ContactOptionRender = () => {
+ const record: Contact | undefined = useRecordContext();
+ if (!record) return null;
+ return (
+ <Stack direction="row" gap={1} alignItems="center">
+ <Avatar record={record} />
+ <Stack>
+ {record.first_name} {record.last_name}
+ <Typography variant="caption" color="text.secondary">
+ {record.title} at {record.company_name}
+ </Typography>
+ </Stack>
+ </Stack>
+ );
+};
+export const contactOptionText = <ContactOptionRender />;
+export const contactInputText = (choice: {
+ first_name: string;
+ last_name: string;
+}) => `${choice.first_name} ${choice.last_name}`;
diff --git a/src/misc/DialogCloseButton.tsx b/src/misc/DialogCloseButton.tsx
index d0a451d8..c68cc4a3 100644
--- a/src/misc/DialogCloseButton.tsx
+++ b/src/misc/DialogCloseButton.tsx
@@ -5,10 +5,12 @@ export const DialogCloseButton = ({
onClose,
top = 8,
right = 8,
+ color,
}: {
onClose: () => void;
top?: number;
right?: number;
+ color?: string;
}) => {
return (
<IconButton
@@ -18,7 +20,7 @@ export const DialogCloseButton = ({
position: 'absolute',
right,
top,
- color: theme => theme.palette.grey[500],
+ color: theme => (color ? color : theme.palette.grey[500]),
}}
>
<CloseIcon />
diff --git a/src/misc/RelativeDate.tsx b/src/misc/RelativeDate.tsx
new file mode 100644
index 00000000..db4f537c
--- /dev/null
+++ b/src/misc/RelativeDate.tsx
@@ -0,0 +1,5 @@
+import { formatRelative } from 'date-fns';
+
+export function RelativeDate({ date }: { date: string }) {
+ return formatRelative(new Date(date), new Date());
+}
diff --git a/src/misc/usePapaParse.tsx b/src/misc/usePapaParse.tsx
new file mode 100644
index 00000000..cd248fc4
--- /dev/null
+++ b/src/misc/usePapaParse.tsx
@@ -0,0 +1,147 @@
+import * as Papa from 'papaparse';
+import { useCallback, useMemo, useRef, useState } from 'react';
+
+type Import =
+ | {
+ state: 'idle';
+ }
+ | {
+ state: 'parsing';
+ }
+ | {
+ state: 'running' | 'complete';
+
+ rowCount: number;
+ importCount: number;
+ errorCount: number;
+
+ // The remaining time in milliseconds
+ remainingTime: number | null;
+ }
+ | {
+ state: 'error';
+
+ error: Error;
+ };
+
+type usePapaParseProps<T> = {
+ // The import batch size
+ batchSize?: number;
+
+ // processBatch returns the number of imported items
+ processBatch(batch: T[]): Promise<void>;
+};
+
+export function usePapaParse<T>({
+ batchSize = 10,
+ processBatch,
+}: usePapaParseProps<T>) {
+ const importIdRef = useRef<number>(0);
+
+ const [importer, setImporter] = useState<Import>({
+ state: 'idle',
+ });
+
+ const reset = useCallback(() => {
+ setImporter({
+ state: 'idle',
+ });
+ importIdRef.current += 1;
+ }, []);
+
+ const parseCsv = useCallback(
+ (file: File) => {
+ setImporter({
+ state: 'parsing',
+ });
+
+ const importId = importIdRef.current;
+ Papa.parse<T>(file, {
+ header: true,
+ skipEmptyLines: true,
+ async complete(results) {
+ if (importIdRef.current !== importId) {
+ return;
+ }
+
+ setImporter({
+ state: 'running',
+ rowCount: results.data.length,
+ errorCount: results.errors.length,
+ importCount: 0,
+ remainingTime: null,
+ });
+
+ let totalTime = 0;
+ for (let i = 0; i < results.data.length; i += batchSize) {
+ if (importIdRef.current !== importId) {
+ return;
+ }
+
+ const batch = results.data.slice(i, i + batchSize);
+ try {
+ const start = Date.now();
+ await processBatch(batch);
+ totalTime += Date.now() - start;
+
+ const meanTime = totalTime / (i + batch.length);
+ setImporter(previous => {
+ if (previous.state === 'running') {
+ const importCount =
+ previous.importCount + batch.length;
+ return {
+ ...previous,
+ importCount,
+ remainingTime:
+ meanTime *
+ (results.data.length - importCount),
+ };
+ }
+ return previous;
+ });
+ } catch (error) {
+ console.error('Failed to import batch', error);
+ setImporter(previous =>
+ previous.state === 'running'
+ ? {
+ ...previous,
+ errorCount:
+ previous.errorCount +
+ batch.length,
+ }
+ : previous
+ );
+ }
+ }
+
+ setImporter(previous =>
+ previous.state === 'running'
+ ? {
+ ...previous,
+ state: 'complete',
+ remainingTime: null,
+ }
+ : previous
+ );
+ },
+ error(error) {
+ setImporter({
+ state: 'error',
+ error,
+ });
+ },
+ dynamicTyping: true,
+ });
+ },
+ [batchSize, processBatch]
+ );
+
+ return useMemo(
+ () => ({
+ importer,
+ parseCsv,
+ reset,
+ }),
+ [importer, parseCsv, reset]
+ );
+}