Skip to content

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

Feat(atomic): Create view for companies and contact + ban users

Anthony Rimetb22ce9192a82
diff --git a/src/companies/CompanyCard.tsx b/src/companies/CompanyCard.tsx
index 30dc68a9..49521418 100644
--- a/src/companies/CompanyCard.tsx
+++ b/src/companies/CompanyCard.tsx
@@ -8,7 +8,6 @@ import {
SelectField,
useRecordContext,
Link,
- ReferenceManyCount,
} from 'react-admin';
import { CompanyAvatar } from './CompanyAvatar';
@@ -62,19 +61,33 @@ export const CompanyCard = (props: { record?: Company }) => {
<Box display="flex" justifyContent="space-around" width="100%">
<Box display="flex" alignItems="center">
<ContactsIcon color="disabled" sx={{ mr: 1 }} />
- <ReferenceManyCount
- label="Nb contacts"
- reference="contacts"
- target="company_id"
- />
+ <div>
+ <Typography variant="subtitle2" sx={{ mb: -1 }}>
+ {record.nb_contacts}
+ </Typography>
+ <Typography variant="caption" color="textSecondary">
+ {record.nb_contacts
+ ? record.nb_contacts > 1
+ ? 'contacts'
+ : 'contact'
+ : 'contact'}
+ </Typography>
+ </div>
</Box>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<DealIcon color="disabled" sx={{ mr: 1 }} />
- <ReferenceManyCount
- label="Nb deals"
- reference="deals"
- target="company_id"
- />
+ <div>
+ <Typography variant="subtitle2" sx={{ mb: -1 }}>
+ {record.nb_deals}
+ </Typography>
+ <Typography variant="caption" color="textSecondary">
+ {record.nb_deals
+ ? record.nb_deals > 1
+ ? 'deals'
+ : 'deal'
+ : 'deal'}
+ </Typography>
+ </div>
</Box>
</Box>
</Paper>
diff --git a/src/companies/CompanyShow.tsx b/src/companies/CompanyShow.tsx
index 2878a623..29e0ea18 100644
--- a/src/companies/CompanyShow.tsx
+++ b/src/companies/CompanyShow.tsx
@@ -15,7 +15,6 @@ import {
import { formatDistance } from 'date-fns';
import {
RecordContextProvider,
- ReferenceManyCount,
ReferenceManyField,
ShowBase,
SortButton,
@@ -71,11 +70,17 @@ const CompanyShowContent = () => {
/>
</TabbedShowLayout.Tab>
<TabbedShowLayout.Tab
- label="Contacts"
+ label={
+ !record.nb_contacts
+ ? 'No Contacts'
+ : record.nb_contacts === 1
+ ? '1 Contact'
+ : `${record.nb_contacts} Contacts`
+ }
path="contacts"
>
<ReferenceManyField
- reference="contacts"
+ reference="contacts_summary"
target="company_id"
sort={{ field: 'last_name', order: 'ASC' }}
>
@@ -85,27 +90,38 @@ const CompanyShowContent = () => {
spacing={2}
mt={1}
>
- <SortButton
- fields={[
- 'last_name',
- 'first_name',
- 'last_seen',
- ]}
- />
+ {!!record.nb_contacts && (
+ <SortButton
+ fields={[
+ 'last_name',
+ 'first_name',
+ 'last_seen',
+ ]}
+ />
+ )}
<CreateRelatedContactButton />
</Stack>
<ContactsIterator />
</ReferenceManyField>
</TabbedShowLayout.Tab>
- <TabbedShowLayout.Tab label="Deals" path="deals">
- <ReferenceManyField
- reference="deals"
- target="company_id"
- sort={{ field: 'name', order: 'ASC' }}
+ {record.nb_deals ? (
+ <TabbedShowLayout.Tab
+ label={
+ record.nb_deals === 1
+ ? '1 deal'
+ : `${record.nb_deals} Deals`
+ }
+ path="deals"
>
- <DealsIterator />
- </ReferenceManyField>
- </TabbedShowLayout.Tab>
+ <ReferenceManyField
+ reference="deals"
+ target="company_id"
+ sort={{ field: 'name', order: 'ASC' }}
+ >
+ <DealsIterator />
+ </ReferenceManyField>
+ </TabbedShowLayout.Tab>
+ ) : null}
</TabbedShowLayout>
</CardContent>
</Card>
@@ -140,12 +156,12 @@ const ContactsIterator = () => {
secondary={
<>
{contact.title}
- {' '}
- <ReferenceManyCount
- reference="tasks"
- target="contact_id"
- />{' '}
- tasks
+ {contact.nb_tasks
+ ? ` - ${contact.nb_tasks} task${
+ contact.nb_tasks > 1 ? 's' : ''
+ }`
+ : ''}
+ &nbsp; &nbsp;
<TagsList />
</>
}
diff --git a/src/contacts/ContactListContent.tsx b/src/contacts/ContactListContent.tsx
index 33b249dc..edc8798d 100644
--- a/src/contacts/ContactListContent.tsx
+++ b/src/contacts/ContactListContent.tsx
@@ -3,7 +3,6 @@ import * as React from 'react';
import {
RecordContextProvider,
ReferenceField,
- ReferenceManyCount,
SimpleListLoading,
TextField,
useListContext,
@@ -84,12 +83,14 @@ export const ContactListContent = () => {
>
<TextField source="name" />
</ReferenceField>
- {' - '}
- <ReferenceManyCount
- reference="tasks"
- target="contact_id"
- />{' '}
- tasks
+ {contact.nb_tasks
+ ? ` - ${contact.nb_tasks} task${
+ contact.nb_tasks > 1
+ ? 's'
+ : ''
+ }`
+ : ''}
+ &nbsp;&nbsp;
<TagsList />
</>
}
diff --git a/src/dashboard/HotContacts.tsx b/src/dashboard/HotContacts.tsx
index 2a078e23..5661bfb0 100644
--- a/src/dashboard/HotContacts.tsx
+++ b/src/dashboard/HotContacts.tsx
@@ -1,14 +1,7 @@
import * as React from 'react';
import { Card, Box, Stack } from '@mui/material';
import ContactsIcon from '@mui/icons-material/Contacts';
-import {
- useGetList,
- Link,
- SimpleList,
- useGetIdentity,
- ReferenceField,
- TextField,
-} from 'react-admin';
+import { useGetList, Link, SimpleList, useGetIdentity } from 'react-admin';
import { Avatar } from '../contacts/Avatar';
import { Contact } from '../types';
@@ -56,14 +49,7 @@ export const HotContacts = () => {
}
secondaryText={contact => (
<>
- {contact.title} at{' '}
- <ReferenceField
- source="company_id"
- reference="companies"
- link={false}
- >
- <TextField source="name" />
- </ReferenceField>
+ {contact.title} at {contact.company_name}
</>
)}
leftAvatar={contact => <Avatar record={contact} />}
diff --git a/src/dataProvider.ts b/src/dataProvider.ts
index 23edd3b8..45443449 100644
--- a/src/dataProvider.ts
+++ b/src/dataProvider.ts
@@ -80,6 +80,27 @@ async function processContactAvatar(
const dataProviderWithCustomMethods = {
...baseDataProvider,
+ async getList(resource: string, params: GetListParams) {
+ if (resource === 'companies') {
+ return baseDataProvider.getList('companies_summary', params);
+ }
+ if (resource === 'contacts') {
+ return baseDataProvider.getList('contacts_summary', params);
+ }
+
+ return baseDataProvider.getList(resource, params);
+ },
+ async getOne(resource: string, params: any) {
+ if (resource === 'companies') {
+ return baseDataProvider.getOne('companies_summary', params);
+ }
+ if (resource === 'contacts') {
+ return baseDataProvider.getOne('contacts_summary', params);
+ }
+
+ return baseDataProvider.getOne(resource, params);
+ },
+
async signUp({ email, password, first_name, last_name }: SignUpData) {
const response = await supabase.auth.signUp({
email,
@@ -218,6 +239,7 @@ export const dataProvider = withLifecycleCallbacks(
return applyFullTextSearch([
'first_name',
'last_name',
+ 'company_name',
'title',
'email',
'phone_number1',
@@ -276,7 +298,7 @@ const applyFullTextSearch = (columns: string[]) => (params: GetListParams) => {
'@or': columns.reduce(
(acc, column) => ({
...acc,
- [`${column}@fts`]: q,
+ [`${column}@ilike`]: q,
}),
{}
),
diff --git a/src/dataProvider/activity.ts b/src/dataProvider/activity.ts
index 6c037908..3262a39c 100644
--- a/src/dataProvider/activity.ts
+++ b/src/dataProvider/activity.ts
@@ -60,8 +60,8 @@ async function getCompaniesLog(
const companies = await dataProvider
.getList<Company>('companies', {
filter: companyId
- ? { id: companyId, sales_id: salesIds }
- : { sales_id: salesIds },
+ ? { id: companyId, 'sales_id@in': `(${salesIds})` }
+ : { 'sales_id@in': `(${salesIds})` },
pagination: { page: 1, perPage: 10_000 },
sort: { field: 'created_at', order: 'DESC' },
})
diff --git a/src/deals/ContactList.tsx b/src/deals/ContactList.tsx
index b8eb0dbe..c26e9834 100644
--- a/src/deals/ContactList.tsx
+++ b/src/deals/ContactList.tsx
@@ -1,5 +1,5 @@
import * as React from 'react';
-import { ReferenceField, TextField, useListContext } from 'react-admin';
+import { useListContext } from 'react-admin';
import { Link, Stack, Typography } from '@mui/material';
import { Link as RouterLink } from 'react-router-dom';
import { Avatar } from '../contacts/Avatar';
@@ -21,14 +21,7 @@ export const ContactList = () => {
{contact.first_name} {contact.last_name}
</Link>
<Typography variant="caption" color="text.secondary">
- {contact.title} at{' '}
- <ReferenceField
- source="company_id"
- reference="companies"
- link={false}
- >
- <TextField source="name" variant="caption" />
- </ReferenceField>
+ {contact.title} at {contact.company_name}
</Typography>
</Stack>
</Stack>
diff --git a/src/deals/DealInputs.tsx b/src/deals/DealInputs.tsx
index 29d05a38..850b0269 100644
--- a/src/deals/DealInputs.tsx
+++ b/src/deals/DealInputs.tsx
@@ -100,7 +100,10 @@ const DealLinkedToInputs = () => {
/>
</ReferenceInput>
- <ReferenceArrayInput source="contact_ids" reference="contacts">
+ <ReferenceArrayInput
+ source="contact_ids"
+ reference="contacts_summary"
+ >
<AutocompleteArrayInput
label="Contacts"
optionText={contactOptionText}
diff --git a/src/login/LoginPage.tsx b/src/login/LoginPage.tsx
index 3e18eadf..595706d0 100644
--- a/src/login/LoginPage.tsx
+++ b/src/login/LoginPage.tsx
@@ -7,12 +7,16 @@ import { LoginSkeleton } from './LoginSkeleton';
export const LoginPage = () => {
const dataProvider = useDataProvider<CustomDataProvider>();
- const { data: isInitialized, error, isPending } = useQuery({
+ const {
+ data: isInitialized,
+ error,
+ isPending,
+ } = useQuery({
queryKey: ['init'],
queryFn: async () => {
return dataProvider.isInitialized();
},
- })
+ });
if (isPending) return <LoginSkeleton />;
if (error) return <LoginForm />;
diff --git a/src/misc/ContactOption.tsx b/src/misc/ContactOption.tsx
index 2054b54b..ea811b79 100644
--- a/src/misc/ContactOption.tsx
+++ b/src/misc/ContactOption.tsx
@@ -1,5 +1,5 @@
import { Stack, Typography } from '@mui/material';
-import { ReferenceField, TextField, useRecordContext } from 'react-admin';
+import { useRecordContext } from 'react-admin';
import { Avatar } from '../contacts/Avatar';
import { Contact } from '../types';
@@ -12,14 +12,7 @@ const ContactOptionRender = () => {
<Stack>
{record.first_name} {record.last_name}
<Typography variant="caption" color="text.secondary">
- {record.title} at{' '}
- <ReferenceField
- source="company_id"
- reference="companies"
- link={false}
- >
- <TextField source="name" variant="caption" />
- </ReferenceField>
+ {record.title} at {record.company_name}
</Typography>
</Stack>
</Stack>
diff --git a/src/tasks/AddTask.tsx b/src/tasks/AddTask.tsx
index e4c8c5a8..2e05622b 100644
--- a/src/tasks/AddTask.tsx
+++ b/src/tasks/AddTask.tsx
@@ -100,7 +100,7 @@ export const AddTask = ({ selectContact }: { selectContact?: boolean }) => {
{selectContact && (
<ReferenceInput
source="contact_id"
- reference="contacts"
+ reference="contacts_summary"
>
<AutocompleteInput
label="Contact"
diff --git a/src/types.ts b/src/types.ts
index 7c55c9b8..6dd68a43 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -56,6 +56,8 @@ export interface Company extends RaRecord {
tax_identifier: string;
country: string;
context_links?: string[];
+ nb_contacts?: number;
+ nb_deals?: number;
}
export interface Contact extends RaRecord {
diff --git a/supabase/functions/users/index.ts b/supabase/functions/users/index.ts
index 34c2087c..9e74b1e3 100644
--- a/supabase/functions/users/index.ts
+++ b/supabase/functions/users/index.ts
@@ -58,6 +58,7 @@ async function inviteUser(req: Request) {
await supabaseServiceClient.auth.admin.createUser({
email,
password,
+ email_confirm: true,
user_metadata: { first_name, last_name },
});
@@ -99,6 +100,7 @@ async function patchUser(req: Request) {
const { data, error: userError } =
await supabaseServiceClient.auth.admin.updateUserById(sale.user_id, {
email,
+ ban_duration: disabled ? '87600h' : 'none',
user_metadata: { first_name, last_name },
});
diff --git a/supabase/migrations/20240730075029_init_db.sql b/supabase/migrations/20240730075029_init_db.sql
index 8b549b4c..4f42ebc6 100644
--- a/supabase/migrations/20240730075029_init_db.sql
+++ b/supabase/migrations/20240730075029_init_db.sql
@@ -558,3 +558,37 @@ values
CREATE POLICY "Attachments 1mt4rzk_0" ON storage.objects FOR SELECT TO authenticated USING (bucket_id = 'attachments');
CREATE POLICY "Attachments 1mt4rzk_1" ON storage.objects FOR INSERT TO authenticated WITH CHECK (bucket_id = 'attachments');
CREATE POLICY "Attachments 1mt4rzk_3" ON storage.objects FOR DELETE TO authenticated USING (bucket_id = 'attachments');
+
+-- Use Postgres to create views for companies.
+
+create view "public"."companies_summary" as
+select
+ c.*,
+ count(distinct d.id) as nb_deals,
+ count(distinct co.id) as nb_contacts
+from
+ "public"."companies" c
+left join
+ "public"."deals" d on c.id = d.company_id
+left join
+ "public"."contacts" co on c.id = co.company_id
+group by
+ c.id;
+
+-- Use Postgres to create views for contacts.
+
+create view "public"."contacts_summary" as
+select
+ co.*,
+ c.name as company_name,
+ count(distinct t.id) as nb_tasks
+from
+ "public"."contacts" co
+left join
+ "public"."tasks" t on co.id = t.contact_id
+left join
+ "public"."companies" c on co.company_id = c.id
+group by
+ co.id, c.name;
+
+