'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withTranslation } from '../lib/i18n'; import {requiresAuthenticatedUser, withPageHelpers, Title, NavButton} from '../lib/page'; import { withForm, Form, FormSendMethod, InputField, TextArea, TableSelect, TableSelectMode, ButtonRow, Button, Fieldset } from '../lib/form'; import axios from '../lib/axios'; import { withErrorHandling, withAsyncErrorHandler } from '../lib/error-handling'; import moment from 'moment'; import { validateNamespace, NamespaceSelect } from '../lib/namespace'; import {DeleteModalDialog} from "../lib/modals"; import mailtrainConfig from 'mailtrainConfig'; import {getUrl} from "../lib/urls"; @withTranslation() @withForm @withPageHelpers @withErrorHandling @requiresAuthenticatedUser export default class CUD extends Component { constructor(props) { super(props); this.state = {}; this.initForm({ onChange: { report_template: ::this.onReportTemplateChange } }); } static propTypes = { action: PropTypes.string.isRequired, entity: PropTypes.object } @withAsyncErrorHandler async fetchUserFields(reportTemplateId) { const result = await axios.get(getUrl(`rest/report-template-user-fields/${reportTemplateId}`)); this.updateFormValue('user_fields', result.data); } onReportTemplateChange(state, key, oldVal, newVal) { if (oldVal !== newVal) { state.formState = state.formState.setIn(['data', 'user_fields', 'value'], ''); if (newVal) { // noinspection JSIgnoredPromiseFromCall this.fetchUserFields(newVal); } } } componentDidMount() { if (this.props.entity) { this.getFormValuesFromEntity(this.props.entity, data => { for (const key in data.params) { data[`param_${key}`] = data.params[key]; } }); } else { this.populateFormValues({ name: '', description: '', report_template: null, namespace: mailtrainConfig.user.namespace, user_fields: null }); } } localValidateFormValues(state) { const t = this.props.t; const edit = this.props.entity; if (!state.getIn(['name', 'value'])) { state.setIn(['name', 'error'], t('nameMustNotBeEmpty')); } else { state.setIn(['name', 'error'], null); } if (!state.getIn(['report_template', 'value'])) { state.setIn(['report_template', 'error'], t('reportTemplateMustBeSelected')); } else { state.setIn(['report_template', 'error'], null); } for (const paramId of state.keys()) { if (paramId.startsWith('param_')) { state.deleteIn([paramId, 'error']); } } const userFieldsSpec = state.getIn(['user_fields', 'value']); if (userFieldsSpec) { for (const spec of userFieldsSpec) { const fldId = `param_${spec.id}`; const selection = state.getIn([fldId, 'value']) || []; if (spec.maxOccurences === 1) { if (spec.minOccurences === 1 && (selection === null || selection === undefined)) { // FIXME - this does not seem to correspond with selectionAsArray state.setIn([fldId, 'error'], t('exactlyOneItemHasToBeSelected')); } } else { if (selection.length < spec.minOccurences) { state.setIn([fldId, 'error'], t('atLeastCountItemsHaveToBeSelected', { count: spec.minOccurences })); } else if (selection.length > spec.maxOccurences) { state.setIn([fldId, 'error'], t('atMostCountItemsCanToBeSelected', { count: spec.maxOccurences })); } } } } validateNamespace(t, state); } async submitHandler() { const t = this.props.t; if (this.getFormValue('report_template') && !this.getFormValue('user_fields')) { this.setFormStatusMessage('warning', t('reportParametersAreNotSelectedWaitFor')); return; } let sendMethod, url; if (this.props.entity) { sendMethod = FormSendMethod.PUT; url = `rest/reports/${this.props.entity.id}` } else { sendMethod = FormSendMethod.POST; url = 'rest/reports' } this.disableForm(); this.setFormStatusMessage('info', t('saving')); const submitSuccessful = await this.validateAndSendFormValuesToURL(sendMethod, url, data => { const params = {}; for (const spec of data.user_fields) { const fldId = `param_${spec.id}`; params[spec.id] = data[fldId]; delete data[fldId]; } delete data.user_fields; data.params = params; }); if (submitSuccessful) { this.navigateToWithFlashMessage('/reports', 'success', t('reportSaved')); } else { this.enableForm(); this.setFormStatusMessage('warning', t('thereAreErrorsInTheFormPleaseFixThemAnd')); } } render() { const t = this.props.t; const isEdit = !!this.props.entity; const canDelete = isEdit && this.props.entity.permissions.includes('delete'); const reportTemplateColumns = [ { data: 1, title: t('name') }, { data: 2, title: t('description') }, { data: 3, title: t('created'), render: data => moment(data).fromNow() } ]; const userFieldsSpec = this.getFormValue('user_fields'); const userFields = []; function addUserFieldTableSelect(spec, dataUrl, selIndex, columns) { let dropdown, selectMode; if (spec.maxOccurences === 1) { dropdown = true; selectMode = TableSelectMode.SINGLE; } else { dropdown = true; selectMode = TableSelectMode.MULTI; } const fld = ; userFields.push(fld); } if (userFieldsSpec) { for (const spec of userFieldsSpec) { if (spec.type === 'campaign') { addUserFieldTableSelect(spec, 'rest/campaigns-table', 1,[ {data: 0, title: "#"}, {data: 1, title: t('name')}, {data: 2, title: t('description')}, {data: 3, title: t('status')}, {data: 4, title: t('created'), render: data => moment(data).fromNow()} ]); } else if (spec.type === 'list') { addUserFieldTableSelect(spec, 'rest/lists-table', 1,[ {data: 0, title: "#"}, {data: 1, title: t('name')}, {data: 2, title: t('id')}, {data: 3, title: t('subscribers')}, {data: 4, title: t('description')} ]); } else { userFields.push(
{t('unknownFieldTypeType', { type: spec.type })}
) } } } return (
{canDelete && } {isEdit ? t('editReport') : t('createReport')}