import { useContext, useRef } from 'react'; import { useApi, useMessages } from 'hooks'; import { Form, FormRow, FormButtons, SubmitButton, PopupTrigger, Icon, Popup } from 'react-basics'; import { ReportContext } from 'components/pages/reports/Report'; import Empty from 'components/common/Empty'; import { DATA_TYPES, REPORT_PARAMETERS } from 'lib/constants'; import Icons from 'components/icons'; import FieldAddForm from './FieldAddForm'; import BaseParameters from '../BaseParameters'; import ParameterList from '../ParameterList'; import styles from './InsightsParameters.module.css'; function useFields(websiteId, startDate, endDate) { const { get, useQuery } = useApi(); const { data, error, isLoading } = useQuery( ['fields', websiteId, startDate, endDate], () => get('/reports/event-data', { websiteId, startAt: +startDate, endAt: +endDate, }), { enabled: !!(websiteId && startDate && endDate) }, ); return { data, error, isLoading }; } export function InsightsParameters() { const { report, runReport, updateReport, isRunning } = useContext(ReportContext); const { formatMessage, labels, messages } = useMessages(); const ref = useRef(null); const { parameters } = report || {}; const { websiteId, dateRange, fields, filters, groups } = parameters || {}; const { startDate, endDate } = dateRange || {}; const queryEnabled = websiteId && dateRange && fields?.length; const { data, error } = useFields(websiteId, startDate, endDate); const parametersSelected = websiteId && startDate && endDate; const hasData = data?.length !== 0; const parameterGroups = [ { label: formatMessage(labels.fields), group: REPORT_PARAMETERS.fields }, { label: formatMessage(labels.filters), group: REPORT_PARAMETERS.filters }, { label: formatMessage(labels.breakdown), group: REPORT_PARAMETERS.groups }, ]; const parameterData = { fields, filters, groups, }; const handleSubmit = values => { runReport(values); }; const handleAdd = (group, value) => { const data = parameterData[group]; if (!data.find(({ name }) => name === value.name)) { updateReport({ parameters: { [group]: data.concat(value) } }); } }; const handleRemove = (group, index) => { const data = [...parameterData[group]]; data.splice(index, 1); updateReport({ parameters: { [group]: data } }); }; const AddButton = ({ group }) => { return ( {(close, element) => { return ( ({ name: eventKey, type: DATA_TYPES[InsightsType], }))} group={group} element={element} onAdd={handleAdd} onClose={close} /> ); }} ); }; return (
{!hasData && } {parametersSelected && hasData && parameterGroups.map(({ label, group }) => { return ( } > handleRemove(group, index)} > {({ name, value }) => { return (
{group === REPORT_PARAMETERS.fields && ( <>
{name}
{value}
)} {group === REPORT_PARAMETERS.filters && ( <>
{name}
{value[0]}
{value[1]}
)} {group === REPORT_PARAMETERS.groups && ( <>
{name}
)}
); }}
); })} {formatMessage(labels.runQuery)} ); } export default InsightsParameters;