Added report context. Removed report store.

This commit is contained in:
Mike Cao 2023-05-28 21:37:34 -07:00
parent bc37f5124e
commit bfb52eb678
31 changed files with 372 additions and 273 deletions

View file

@ -1,42 +1,62 @@
import { Flexbox, Icon, LoadingButton, Text, useToast } from 'react-basics';
import { useContext } from 'react';
import { useRouter } from 'next/router';
import { Flexbox, Icon, LoadingButton, InlineEditField, useToast } from 'react-basics';
import WebsiteSelect from 'components/input/WebsiteSelect';
import PageHeader from 'components/layout/PageHeader';
import DateFilter from 'components/input/DateFilter';
import { parseDateRange } from 'lib/date';
import { updateReport } from 'store/reports';
import { useMessages, useApi } from 'hooks';
import { ReportContext } from './Report';
import styles from './reports.module.css';
export function ReportHeader({ report, icon }) {
export function ReportHeader({ icon }) {
const { report, updateReport } = useContext(ReportContext);
const { formatMessage, labels, messages } = useMessages();
const { toast, showToast } = useToast();
const { post, useMutation } = useApi();
const { mutate, isLoading } = useMutation(data => post(`/reports`, data));
const router = useRouter();
const { mutate: create, isLoading: isCreating } = useMutation(data => post(`/reports`, data));
const { mutate: update, isLoading: isUpdating } = useMutation(data =>
post(`/reports/${data.id}`, data),
);
const { id, websiteId, name, parameters } = report || {};
const { value, startDate, endDate } = parameters?.dateRange || {};
const { websiteId, name, dateRange } = report || {};
const { value, startDate, endDate } = dateRange || {};
const handleSelect = websiteId => {
updateReport(id, { websiteId });
updateReport({ websiteId });
};
const handleDateChange = value => {
updateReport(id, { parameters: { dateRange: { ...parseDateRange(value) } } });
updateReport({ dateRange: { ...parseDateRange(value) } });
};
const handleSave = async () => {
mutate(report, {
onSuccess: async () => {
showToast({ message: formatMessage(messages.saved), variant: 'success' });
},
});
if (!report.id) {
create(report, {
onSuccess: async ({ id }) => {
router.push(`/reports/${id}`, null, { shallow: true });
showToast({ message: formatMessage(messages.saved), variant: 'success' });
},
});
} else {
update(report, {
onSuccess: async () => {
showToast({ message: formatMessage(messages.saved), variant: 'success' });
},
});
}
};
const handleNameChange = name => {
updateReport({ name });
};
const Title = () => {
return (
<>
<Icon size="lg">{icon}</Icon>
<Text>{name}</Text>
<InlineEditField value={name} onCommit={handleNameChange} />
</>
);
};
@ -54,7 +74,7 @@ export function ReportHeader({ report, icon }) {
<WebsiteSelect websiteId={websiteId} onSelect={handleSelect} />
<LoadingButton
variant="primary"
loading={isLoading}
loading={isCreating || isUpdating}
disabled={!websiteId || !value}
onClick={handleSave}
>