Refactoring a common pattern for "clone for existing". Applied to custom forms and templates.
This commit is contained in:
parent
6eeef7a991
commit
d247893d31
8 changed files with 95 additions and 98 deletions
|
@ -28,7 +28,6 @@
|
|||
"datatables.net": "^1.10.19",
|
||||
"datatables.net-bs4": "^1.10.19",
|
||||
"ellipsize": "^0.1.0",
|
||||
"fast-deep-equal": "^2.0.1",
|
||||
"grapesjs": "^0.14.62",
|
||||
"grapesjs-mjml": "0.0.31",
|
||||
"grapesjs-preset-newsletter": "^0.2.20",
|
||||
|
|
|
@ -12,7 +12,6 @@ import {TreeSelectMode, TreeTable} from './tree';
|
|||
import {Table, TableSelectMode} from './table';
|
||||
import {Button} from "./bootstrap-components";
|
||||
import {SketchPicker} from 'react-color';
|
||||
import deepEqual from "fast-deep-equal";
|
||||
|
||||
import ACEEditorRaw from 'react-ace';
|
||||
import 'brace/theme/github';
|
||||
|
@ -1373,7 +1372,24 @@ const withForm = createComponentMixin([], [], (TargetClass, InnerClass) => {
|
|||
const currentData = getSaveData(self, self.state.formState.get('data'));
|
||||
const savedData = self.state.formState.get('savedData');
|
||||
|
||||
return !deepEqual(currentData, savedData);
|
||||
function isDifferent(data1, data2, prefix) {
|
||||
if (typeof data1 === 'object' && typeof data2 === 'object') {
|
||||
const keys = new Set([...Object.keys(data1), ...Object.keys(data2)]);
|
||||
for (const key of keys) {
|
||||
if (isDifferent(data1[key], data2[key], `${prefix}/${key}`)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else if (data1 !== data2) {
|
||||
// console.log(prefix);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const result = isDifferent(currentData, savedData, '');
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
proto.isFormChanged = function() {
|
||||
|
|
|
@ -46,9 +46,7 @@ export default class CUD extends Component {
|
|||
|
||||
this.state = {
|
||||
previewContents: null,
|
||||
previewFullscreen: false,
|
||||
fromSourceCustomForms: false,
|
||||
sourceCustomForms: null,
|
||||
previewFullscreen: false
|
||||
};
|
||||
|
||||
this.serverValidatedFields = [
|
||||
|
@ -300,7 +298,10 @@ export default class CUD extends Component {
|
|||
}
|
||||
|
||||
submitFormValuesMutator(data) {
|
||||
return filterData(data, ['name', 'description', 'layout', 'form_input_style', 'namespace',
|
||||
return filterData(data, ['name', 'description', 'namespace',
|
||||
'fromExistingEntity', 'existingEntity',
|
||||
|
||||
'layout', 'form_input_style',
|
||||
'web_subscribe',
|
||||
'web_confirm_subscription_notice',
|
||||
'mail_confirm_subscription_html',
|
||||
|
@ -333,8 +334,8 @@ export default class CUD extends Component {
|
|||
const data = {
|
||||
name: '',
|
||||
description: '',
|
||||
fromSourceCustomForms: false,
|
||||
sourceCustomForms: null,
|
||||
fromExistingEntity: false,
|
||||
existingEntity: null,
|
||||
selectedTemplate: 'layout',
|
||||
namespace: mailtrainConfig.user.namespace
|
||||
};
|
||||
|
@ -355,12 +356,13 @@ export default class CUD extends Component {
|
|||
|
||||
validateNamespace(t, state);
|
||||
|
||||
if (state.getIn(['fromSourceCustomForms', 'value']) && !state.getIn(['sourceCustomForms', 'value'])) {
|
||||
state.setIn(['sourceCustomForms', 'error'], t('sourceCustomFormsMustNotBeEmpty'));
|
||||
if (state.getIn(['fromExistingEntity', 'value']) && !state.getIn(['existingEntity', 'value'])) {
|
||||
state.setIn(['existingEntity', 'error'], t('sourceCustomFormsMustNotBeEmpty'));
|
||||
} else {
|
||||
state.setIn(['sourceCustomForms', 'error'], null);
|
||||
state.setIn(['existingEntity', 'error'], null);
|
||||
}
|
||||
|
||||
|
||||
let formsServerValidationRunning = false;
|
||||
const formsErrors = [];
|
||||
|
||||
|
@ -400,11 +402,7 @@ export default class CUD extends Component {
|
|||
url = `rest/forms/${this.props.entity.id}`;
|
||||
} else {
|
||||
sendMethod = FormSendMethod.POST;
|
||||
if (this.getFormValue('sourceCustomForms') !== null) {
|
||||
url = `rest/forms/${this.getFormValue('sourceCustomForms')}`;
|
||||
} else {
|
||||
url = 'rest/forms';
|
||||
}
|
||||
url = 'rest/forms';
|
||||
}
|
||||
|
||||
this.disableForm();
|
||||
|
@ -510,18 +508,17 @@ export default class CUD extends Component {
|
|||
<NamespaceSelect/>
|
||||
|
||||
{!isEdit &&
|
||||
<CheckBox id="fromSourceCustomForms" label={t('customForms')} text={t('cloneFromAnExistingCustomForms')}/>
|
||||
<CheckBox id="fromExistingEntity" label={t('customForms')} text={t('cloneFromAnExistingCustomForms')}/>
|
||||
}
|
||||
|
||||
{this.getFormValue('fromSourceCustomForms') &&
|
||||
<TableSelect key="sourceCustomFormsKey" id="sourceCustomForms" withHeader dropdown dataUrl='rest/forms-table' columns={customFormsColumns} selectionLabelIndex={1} />
|
||||
}
|
||||
{this.getFormValue('fromExistingEntity') ?
|
||||
<TableSelect id="existingEntity" label={t('Source custom forms')} withHeader dropdown dataUrl='rest/forms-table' columns={customFormsColumns} selectionLabelIndex={1} />
|
||||
:
|
||||
<>
|
||||
<Fieldset label={t('formsPreview')}>
|
||||
<TableSelect id="previewList" label={t('listToPreviewOn')} withHeader dropdown dataUrl='rest/lists-table' columns={listsColumns} selectionLabelIndex={1} help={t('selectListWhoseFieldsWillBeUsedToPreview')}/>
|
||||
|
||||
{!this.getFormValue('fromSourceCustomForms') &&
|
||||
<Fieldset label={t('formsPreview')}>
|
||||
<TableSelect id="previewList" label={t('listToPreviewOn')} withHeader dropdown dataUrl='rest/lists-table' columns={listsColumns} selectionLabelIndex={1} help={t('selectListWhoseFieldsWillBeUsedToPreview')}/>
|
||||
|
||||
{ previewListId &&
|
||||
{ previewListId &&
|
||||
<div>
|
||||
<AlignedRow>
|
||||
<div>
|
||||
|
@ -570,15 +567,16 @@ export default class CUD extends Component {
|
|||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</Fieldset>
|
||||
}
|
||||
}
|
||||
</Fieldset>
|
||||
|
||||
{ selectedTemplate &&
|
||||
<Fieldset label={t('templates')}>
|
||||
<Dropdown id="selectedTemplate" label={t('edit')} options={templateOptGroups} help={this.templateSettings[selectedTemplate].help}/>
|
||||
<ACEEditor id={selectedTemplate} height="500px" mode={this.templateSettings[selectedTemplate].mode}/>
|
||||
</Fieldset>
|
||||
{ selectedTemplate &&
|
||||
<Fieldset label={t('templates')}>
|
||||
<Dropdown id="selectedTemplate" label={t('edit')} options={templateOptGroups} help={this.templateSettings[selectedTemplate].help}/>
|
||||
<ACEEditor id={selectedTemplate} height="500px" mode={this.templateSettings[selectedTemplate].mode}/>
|
||||
</Fieldset>
|
||||
}
|
||||
</>
|
||||
}
|
||||
|
||||
<ButtonRow>
|
||||
|
|
|
@ -98,7 +98,8 @@ export default class CUD extends Component {
|
|||
|
||||
submitFormValuesMutator(data) {
|
||||
this.templateTypes[data.type].beforeSave(data);
|
||||
return filterData(data, ['name', 'description', 'type', 'tag_language', 'data', 'html', 'text', 'namespace']);
|
||||
|
||||
return filterData(data, ['name', 'description', 'type', 'tag_language', 'data', 'html', 'text', 'namespace', 'fromExistingEntity', 'existingEntity']);
|
||||
}
|
||||
|
||||
async getPreSubmitFormValuesUpdater() {
|
||||
|
@ -127,8 +128,8 @@ export default class CUD extends Component {
|
|||
type: mailtrainConfig.editors[0],
|
||||
tag_language: mailtrainConfig.tagLanguages[0],
|
||||
|
||||
fromSourceTemplate: false,
|
||||
sourceTemplate: null,
|
||||
fromExistingEntity: false,
|
||||
existingEntity: null,
|
||||
|
||||
text: '',
|
||||
html: '',
|
||||
|
@ -158,10 +159,10 @@ export default class CUD extends Component {
|
|||
state.setIn(['tag_language', 'error'], t('Tag language must be selected'));
|
||||
}
|
||||
|
||||
if (state.getIn(['fromSourceTemplate', 'value']) && !state.getIn(['sourceTemplate', 'value'])) {
|
||||
state.setIn(['sourceTemplate', 'error'], t('sourceTemplateMustNotBeEmpty'));
|
||||
if (state.getIn(['fromExistingEntity', 'value']) && !state.getIn(['existingEntity', 'value'])) {
|
||||
state.setIn(['existingEntity', 'error'], t('sourceTemplateMustNotBeEmpty'));
|
||||
} else {
|
||||
state.setIn(['sourceTemplate', 'error'], null);
|
||||
state.setIn(['existingEntity', 'error'], null);
|
||||
}
|
||||
|
||||
validateNamespace(t, state);
|
||||
|
@ -350,11 +351,11 @@ export default class CUD extends Component {
|
|||
<TextArea id="description" label={t('description')}/>
|
||||
|
||||
{!isEdit &&
|
||||
<CheckBox id="fromSourceTemplate" label={t('template')} text={t('cloneFromAnExistingTemplate')}/>
|
||||
<CheckBox id="fromExistingEntity" label={t('template')} text={t('cloneFromAnExistingTemplate')}/>
|
||||
}
|
||||
|
||||
{this.getFormValue('fromSourceTemplate') ?
|
||||
<TableSelect key="templateSelect" id="sourceTemplate" withHeader dropdown dataUrl='rest/templates-table' columns={templatesColumns} selectionLabelIndex={1} />
|
||||
{this.getFormValue('fromExistingEntity') ?
|
||||
<TableSelect id="existingEntity" label={t('Source template')} withHeader dropdown dataUrl='rest/templates-table' columns={templatesColumns} selectionLabelIndex={1} />
|
||||
:
|
||||
<>
|
||||
{isEdit ?
|
||||
|
@ -366,11 +367,11 @@ export default class CUD extends Component {
|
|||
}
|
||||
|
||||
{typeForm}
|
||||
|
||||
<Dropdown id="tag_language" label={t('Tag language')} options={tagLanguageOptions} disabled={isEdit && (!typeKey || this.templateTypes[typeKey].isTagLanguageSelectorDisabledForEdit)}/>
|
||||
</>
|
||||
}
|
||||
|
||||
<Dropdown id="tag_language" label={t('Tag language')} options={tagLanguageOptions} disabled={isEdit && (!typeKey || this.templateTypes[typeKey].isTagLanguageSelectorDisabledForEdit)}/>
|
||||
|
||||
<NamespaceSelect/>
|
||||
|
||||
{editForm}
|
||||
|
|
|
@ -924,7 +924,7 @@
|
|||
"editTemplate": "Edit Template",
|
||||
"createTemplate": "Create Template",
|
||||
"cloneFromAnExistingTemplate": "Clone from an existing template",
|
||||
"cloneFromAnExistingCustomForms": "Clone from an existing custom forms",
|
||||
"cloneFromAnExistingCustomForms": "Clone from existing custom forms",
|
||||
"mosaico": "Mosaico",
|
||||
"templateContentHtml": "Template content (HTML)",
|
||||
"mosaicoTemplateDesigner": "Mosaico Template Designer",
|
||||
|
|
|
@ -70,7 +70,7 @@ async function listDTAjax(context, params) {
|
|||
}
|
||||
|
||||
|
||||
async function _getById(tx, id) {
|
||||
async function _getByIdTx(tx, id) {
|
||||
const entity = await tx('custom_forms').where('id', id).first();
|
||||
|
||||
if (!entity) {
|
||||
|
@ -86,17 +86,20 @@ async function _getById(tx, id) {
|
|||
return entity;
|
||||
}
|
||||
|
||||
async function getByIdTx(tx, context, id, withPermissions = true) {
|
||||
await shares.enforceEntityPermissionTx(tx, context, 'customForm', id, 'view');
|
||||
const entity = await _getByIdTx(tx, id);
|
||||
|
||||
if (withPermissions) {
|
||||
entity.permissions = await shares.getPermissionsTx(tx, context, 'customForm', id);
|
||||
}
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
async function getById(context, id, withPermissions = true) {
|
||||
return await knex.transaction(async tx => {
|
||||
await shares.enforceEntityPermissionTx(tx, context, 'customForm', id, 'view');
|
||||
const entity = await _getById(tx, id);
|
||||
|
||||
if (withPermissions) {
|
||||
entity.permissions = await shares.getPermissionsTx(tx, context, 'customForm', id);
|
||||
}
|
||||
|
||||
return entity;
|
||||
return await getByIdTx(tx, context, id, withPermissions);
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -122,6 +125,17 @@ async function create(context, entity) {
|
|||
return await knex.transaction(async tx => {
|
||||
await shares.enforceEntityPermissionTx(tx, context, 'namespace', entity.namespace, 'createCustomForm');
|
||||
|
||||
if (entity.fromExistingEntity) {
|
||||
const existing = await getByIdTx(tx, context, entity.existingEntity, false);
|
||||
|
||||
entity.layout = existing.layout;
|
||||
entity.form_input_style = existing.form_input_style;
|
||||
|
||||
for (const key of allowedFormKeys) {
|
||||
entity[key] = existing[key];
|
||||
}
|
||||
}
|
||||
|
||||
await namespaceHelpers.validateEntity(tx, entity);
|
||||
|
||||
const form = filterObject(entity, allowedFormKeys);
|
||||
|
@ -147,7 +161,7 @@ async function updateWithConsistencyCheck(context, entity) {
|
|||
await knex.transaction(async tx => {
|
||||
await shares.enforceEntityPermissionTx(tx, context, 'customForm', entity.id, 'edit');
|
||||
|
||||
const existing = await _getById(tx, entity.id);
|
||||
const existing = await _getByIdTx(tx, entity.id);
|
||||
|
||||
const existingHash = hash(existing);
|
||||
if (existingHash !== entity.originalHash) {
|
||||
|
@ -175,31 +189,6 @@ async function updateWithConsistencyCheck(context, entity) {
|
|||
});
|
||||
}
|
||||
|
||||
async function copy(context, entity, formId) {
|
||||
return await knex.transaction(async tx => {
|
||||
await shares.enforceEntityPermissionTx(tx, context, 'namespace', entity.namespace, 'createCustomForm');
|
||||
const existing = await _getById(tx, formId);
|
||||
await namespaceHelpers.validateEntity(tx, entity);
|
||||
|
||||
const form = filterObject(existing, allowedFormKeys);
|
||||
enforce(!Object.keys(checkForMjmlErrors(form)).length, 'Error(s) in form templates');
|
||||
|
||||
const ids = await tx('custom_forms').insert(filterObject(entity, formAllowedKeys));
|
||||
const id = ids[0];
|
||||
|
||||
for (const formKey in form) {
|
||||
await tx('custom_forms_data').insert({
|
||||
form: id,
|
||||
data_key: formKey,
|
||||
data_value: form[formKey]
|
||||
})
|
||||
}
|
||||
|
||||
await shares.rebuildPermissionsTx(tx, { entityTypeId: 'customForm', entityId: id });
|
||||
return id;
|
||||
});
|
||||
}
|
||||
|
||||
async function remove(context, id) {
|
||||
await knex.transaction(async tx => {
|
||||
await shares.enforceEntityPermissionTx(tx, context, 'customForm', id, 'delete');
|
||||
|
@ -308,9 +297,9 @@ function checkForMjmlErrors(form) {
|
|||
module.exports.listDTAjax = listDTAjax;
|
||||
module.exports.hash = hash;
|
||||
module.exports.getById = getById;
|
||||
module.exports.getByIdTx = getByIdTx;
|
||||
module.exports.create = create;
|
||||
module.exports.updateWithConsistencyCheck = updateWithConsistencyCheck;
|
||||
module.exports.copy = copy;
|
||||
module.exports.remove = remove;
|
||||
module.exports.getDefaultCustomFormValues = getDefaultCustomFormValues;
|
||||
module.exports.serverValidate = serverValidate;
|
||||
|
|
|
@ -75,14 +75,14 @@ async function create(context, entity) {
|
|||
return await knex.transaction(async tx => {
|
||||
await shares.enforceEntityPermissionTx(tx, context, 'namespace', entity.namespace, 'createTemplate');
|
||||
|
||||
if (entity.fromSourceTemplate) {
|
||||
const template = await getByIdTx(tx, context, entity.sourceTemplate, false);
|
||||
if (entity.fromExistingEntity) {
|
||||
const existing = await getByIdTx(tx, context, entity.existingEntity, false);
|
||||
|
||||
entity.type = template.type;
|
||||
entity.tag_language = template.tag_language;
|
||||
entity.data = template.data;
|
||||
entity.html = template.html;
|
||||
entity.text = template.text;
|
||||
entity.type = existing.type;
|
||||
entity.tag_language = existing.tag_language;
|
||||
entity.data = existing.data;
|
||||
entity.html = existing.html;
|
||||
entity.text = existing.text;
|
||||
}
|
||||
|
||||
await _validateAndPreprocess(tx, entity);
|
||||
|
@ -92,10 +92,10 @@ async function create(context, entity) {
|
|||
|
||||
await shares.rebuildPermissionsTx(tx, { entityTypeId: 'template', entityId: id });
|
||||
|
||||
if (entity.fromSourceTemplate) {
|
||||
await files.copyAllTx(tx, context, 'template', 'file', entity.sourceTemplate, 'template', 'file', id);
|
||||
if (entity.fromExistingEntity) {
|
||||
await files.copyAllTx(tx, context, 'template', 'file', entity.existingEntity, 'template', 'file', id);
|
||||
|
||||
convertFileURLs(entity, 'template', entity.sourceTemplate, 'template', id);
|
||||
convertFileURLs(entity, 'template', entity.existingEntity, 'template', id);
|
||||
await tx('templates').update(filterObject(entity, allowedKeys)).where('id', id);
|
||||
}
|
||||
|
||||
|
|
|
@ -26,12 +26,6 @@ router.postAsync('/forms', passport.loggedIn, passport.csrfProtection, async (re
|
|||
return res.json(await forms.create(req.context, req.body));
|
||||
});
|
||||
|
||||
router.postAsync('/forms/:formId', passport.loggedIn, passport.csrfProtection, async (req, res) => {
|
||||
const entity = req.body;
|
||||
const formId= castToInteger(req.params.formId);
|
||||
return res.json(await forms.copy(req.context, entity, formId));
|
||||
});
|
||||
|
||||
router.putAsync('/forms/:formId', passport.loggedIn, passport.csrfProtection, async (req, res) => {
|
||||
const entity = req.body;
|
||||
entity.id = castToInteger(req.params.formId);
|
||||
|
|
Loading…
Reference in a new issue