umami/components/pages/reports/ReportHeader.js

84 lines
2.5 KiB
JavaScript
Raw Normal View History

import { useContext } from 'react';
import { useRouter } from 'next/router';
2023-06-05 12:08:43 +02:00
import { Icon, LoadingButton, InlineEditField, useToast } from 'react-basics';
2023-05-18 08:20:06 +02:00
import PageHeader from 'components/layout/PageHeader';
2023-05-20 18:02:08 +02:00
import { useMessages, useApi } from 'hooks';
import { ReportContext } from './Report';
2023-06-05 12:08:43 +02:00
import styles from './ReportHeader.module.css';
import reportStyles from './reports.module.css';
2023-05-18 08:20:06 +02:00
export function ReportHeader({ icon }) {
const { report, updateReport } = useContext(ReportContext);
2023-05-20 18:02:08 +02:00
const { formatMessage, labels, messages } = useMessages();
const { toast, showToast } = useToast();
const { post, useMutation } = useApi();
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),
);
2023-05-18 08:20:06 +02:00
2023-06-05 12:08:43 +02:00
const { name, description, parameters } = report || {};
2023-05-31 01:49:22 +02:00
const { websiteId, dateRange } = parameters || {};
2023-05-18 08:20:06 +02:00
2023-05-20 18:02:08 +02:00
const handleSave = async () => {
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 });
2023-05-20 18:02:08 +02:00
};
2023-05-18 08:20:06 +02:00
2023-06-05 12:08:43 +02:00
const handleDescriptionChange = description => {
updateReport({ description });
};
2023-05-18 08:20:06 +02:00
const Title = () => {
return (
<>
2023-05-20 18:02:08 +02:00
<Icon size="lg">{icon}</Icon>
2023-06-05 12:08:43 +02:00
<InlineEditField name="name" value={name} onCommit={handleNameChange} />
2023-05-18 08:20:06 +02:00
</>
);
};
return (
2023-06-05 12:08:43 +02:00
<div className={reportStyles.header}>
<PageHeader title={<Title />}>
<LoadingButton
variant="primary"
loading={isCreating || isUpdating}
disabled={!websiteId || !dateRange?.value || !name}
onClick={handleSave}
>
{formatMessage(labels.save)}
</LoadingButton>
</PageHeader>
<div className={styles.description}>
<InlineEditField
name="description"
value={description}
placeholder={`+ ${formatMessage(labels.addDescription)}`}
onCommit={handleDescriptionChange}
/>
</div>
2023-05-20 18:02:08 +02:00
{toast}
2023-06-05 12:08:43 +02:00
</div>
2023-05-18 08:20:06 +02:00
);
}
2023-05-20 18:02:08 +02:00
export default ReportHeader;