Files
raven-client/ayanova/src/views/adm-global-select-templates.vue
2020-04-05 19:01:54 +00:00

533 lines
15 KiB
Vue

<template>
<v-container>
<v-row v-if="formState.ready">
<v-col>
<v-form ref="form">
<!-- Prevent implicit submission of the form on enter key, this is not necessary on a form with a text area which is why I never noticed it with the other forms -->
<button
type="submit"
disabled
style="display: none"
aria-hidden="true"
></button>
<v-row>
<gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
<v-col cols="12">
<v-select
v-model="templateId"
:items="selectLists.pickListTemplates"
item-text="name"
item-value="id"
:label="$ay.t('PickListTemplates')"
@input="templateSelected"
:data-cy="!!$ay.dev ? 'SelectTemplate' : false"
:disabled="formState.dirty"
>
</v-select>
</v-col>
<!-- <div>WORKING ARRAY: {{ workingArray }}</div> -->
<!-- <div>
TEMPLATE:
{{ obj }}
</div>
<div>
available fields:
{{ availableFields }}
</div> -->
<template v-for="(item, index) in workingArray">
<v-col :key="item.key" cols="12" sm="6" lg="4" xl="3" px-2>
<v-card>
<v-card-title>
{{ item.title }}
</v-card-title>
<v-card-subtitle>
{{ item.key }}
</v-card-subtitle>
<v-card-text>
<v-checkbox
v-model="item.include"
:readOnly="formState.readOnly"
:label="$ay.t('Include')"
:ref="item.key"
:disabled="item.required"
@change="includeChanged(item)"
:data-cy="!!$ay.dev ? item.key + 'Include' : false"
></v-checkbox>
<!-- RE-ORDER CONTROL -->
<div class="d-flex justify-space-between">
<v-btn large icon @click="move('start', index)"
><v-icon large>fa-step-backward</v-icon></v-btn
>
<v-btn large icon @click="move('left', index)"
><v-icon large>fa-backward</v-icon></v-btn
>
<v-btn large icon @click="move('right', index)"
><v-icon large>fa-forward</v-icon></v-btn
>
<v-btn large icon @click="move('end', index)"
><v-icon large>fa-step-forward</v-icon></v-btn
>
</div>
</v-card-text>
</v-card>
</v-col>
</template>
</v-row>
</v-form>
</v-col>
</v-row>
</v-container>
</template>
<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Xeslint-disable */
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//NOTE: This is a simple form with no need for business rules or validation so stripped out any extraneous code related to all that
//
const FORM_KEY = "adm-global-select-templates";
const API_BASE_URL = "PickList/Template/";
export default {
beforeRouteLeave(to, from, next) {
//let vm = this;
if (this.formState.dirty) {
window.$gz.dialog.confirmLeaveUnsaved().then(dialogResult => {
if (dialogResult == true) {
next();
} else {
next(false);
}
});
} else {
next();
}
},
beforeDestroy() {
window.$gz.eventBus.$off("menu-click", clickHandler);
},
created() {
let vm = this;
initForm(vm)
.then(() => {
vm.formState.ready = true;
vm.readOnly = !vm.rights.change;
window.$gz.eventBus.$on("menu-click", clickHandler);
//NOTE: this would normally be in getDataFromAPI but this form doesn't really need that function so doing it here
//modify the menu as necessary
generateMenu(vm, false); //default is never read only and passing in this vm
//init disable save button so it can be enabled only on edit to show dirty form
window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":delete");
vm.formState.loading = false;
})
.catch(err => {
vm.formState.ready = true;
window.$gz.errorHandler.handleFormError(err, vm);
});
},
data() {
return {
obj: {
id: null,
concurrencyToken: null,
template: null
},
selectLists: {
pickListTemplates: []
},
availableFields: [],
workingArray: [],
fieldKeys: [],
templateId: 0,
lastFetchedTemplateId: 0,
formState: {
ready: false,
dirty: false,
valid: true,
readOnly: false,
loading: true,
errorBoxMessage: null,
appError: null,
serverError: {}
},
rights: window.$gz.role.getRights(window.$gz.type.FormCustom)
};
}, //WATCHERS
watch: {
formState: {
handler: function(val) {
//,oldval is available here too if necessary
if (this.formState.loading) {
return;
}
//enable / disable save button
let canSave = val.dirty && val.valid && !val.readOnly;
if (canSave) {
window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
} else {
window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
}
},
deep: true
},
templateId(val) {
if (val) {
window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":delete");
} else {
window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":delete");
}
}
},
methods: {
includeChanged: function(item) {
window.$gz.form.setFormState({
vm: this,
dirty: true
});
},
move: function(direction, index) {
let totalItems = this.workingArray.length;
let newIndex = 0;
//calculate new index
switch (direction) {
case "start":
newIndex = 0;
break;
case "left":
newIndex = index - 1;
if (newIndex < 0) {
newIndex = 0;
}
break;
case "right":
newIndex = index + 1;
if (newIndex > totalItems - 1) {
newIndex = totalItems - 1;
}
break;
case "end":
newIndex = totalItems - 1;
break;
}
this.workingArray.splice(
newIndex,
0,
this.workingArray.splice(index, 1)[0]
);
window.$gz.form.setFormState({
vm: this,
dirty: true
});
},
templateSelected: function() {
let vm = this;
if (vm.lastFetchedTemplateId == vm.templateId) {
return; //no change
}
vm.workingArray = [];
if (!vm.templateId || vm.templateId == 0) {
vm.lastFetchedTemplateId = 0;
return;
} else {
vm.getDataFromApi();
}
},
getDataFromApi() {
let vm = this;
vm.formState.loading = true;
if (!vm.templateId || vm.templateId == 0) {
return;
}
vm.lastFetchedTemplateId = vm.templateId;
window.$gz.form.deleteAllErrorBoxErrors(vm);
//get available fields
window.$gz.api
.get(API_BASE_URL + "ListFields/" + vm.templateId)
.then(res => {
if (res.error != undefined) {
vm.formState.serverError = res.error;
window.$gz.form.setErrorBoxErrors(vm);
} else {
vm.availableFields = res.data;
vm.fieldKeys = [];
for (let i = 0; i < res.data.length; i++) {
vm.fieldKeys.push(res.data[i].tKey);
}
return window.$gz.translation.fetch(vm.fieldKeys);
}
})
.then(function() {
//weirdly, this wasn't working properly until I put it in a function, it was just executing immediately before translations were resolved from fetch above
//get current edited template
window.$gz.api.get(API_BASE_URL + vm.templateId).then(res => {
if (res.error != undefined) {
vm.formState.serverError = res.error;
window.$gz.form.setErrorBoxErrors(vm);
} else {
vm.obj = res.data;
synthesizeWorkingArray(vm);
//Update the form status
window.$gz.form.setFormState({
vm: vm,
dirty: false,
valid: true,
loading: false,
readOnly: res.readOnly ? true : false
});
}
});
})
.catch(function handleGetDataFromAPIError(error) {
//Update the form status
window.$gz.form.setFormState({
vm: vm,
loading: false
});
window.$gz.errorHandler.handleFormError(error, vm);
});
},
submit() {
let vm = this;
let url = API_BASE_URL;
//clear any errors vm might be around from previous submit
window.$gz.form.deleteAllErrorBoxErrors(vm);
//Create template data object here....
//Note that server expects to see a string array of json template, not actual json
let newObj = {
id: vm.templateId,
template: "[]"
};
//temporary array to hold template for later stringification
let temp = [];
for (let i = 0; i < vm.workingArray.length; i++) {
let ti = vm.workingArray[i];
if (ti.include == true) {
temp.push({
fld: ti.key
});
}
}
//now set the template as a json string
newObj.template = JSON.stringify(temp);
window.$gz.api
.upsert(url, newObj)
.then(res => {
vm.formState.loading = false;
if (res.error != undefined) {
vm.formState.serverError = res.error;
window.$gz.form.setErrorBoxErrors(vm);
} else {
//It's a 204 no data response so no error means it's ok
//form is now clean
window.$gz.form.setFormState({
vm: vm,
dirty: false
});
}
})
.catch(function handleSubmitError(error) {
vm.formState.loading = false;
window.$gz.errorHandler.handleFormError(error, vm);
});
},
remove() {
let vm = this;
window.$gz.dialog.confirmGeneric("ResetToDefault").then(dialogResult => {
if (dialogResult == true) {
//do the delete
vm.formState.loading = true;
//No need to delete a new record, just abandon it...
if (vm.templateId && vm.templateId != 0) {
let url = API_BASE_URL + vm.templateId;
window.$gz.form.deleteAllErrorBoxErrors(vm);
window.$gz.api
.remove(url)
.then(res => {
if (res.error != undefined) {
vm.formState.serverError = res.error;
window.$gz.form.setErrorBoxErrors(vm);
} else {
//trigger reload of form
this.getDataFromApi();
}
})
.catch(function handleGetDataFromAPIError(error) {
//Update the form status
window.$gz.form.setFormState({
vm: vm,
loading: false
});
window.$gz.errorHandler.handleFormError(error, vm);
});
}
}
});
}
}
};
/////////////////////////////
//
//
function clickHandler(menuItem) {
if (!menuItem) {
return;
}
let m = window.$gz.menu.parseMenuItem(menuItem);
if (m.owner == FORM_KEY && !m.disabled) {
switch (m.key) {
case "save":
m.vm.submit();
break;
case "delete":
m.vm.remove();
break;
default:
window.$gz.eventBus.$emit(
"notify-warning",
FORM_KEY + "::context click: [" + m.key + "]"
);
}
}
}
//////////////////////
//
//
function generateMenu(vm) {
let menuOptions = {
isMain: false,
icon: null,
title: vm.$ay.t("PickListTemplates"),
helpUrl: "form-adm-global-select-templates",
formData: {
ayaType: window.$gz.type.FormCustom,
formCustomTemplateKey: undefined
},
menuItems: []
};
if (vm.rights.change) {
menuOptions.menuItems.push({
title: vm.$ay.t("Save"),
icon: "fa-save",
surface: true,
key: FORM_KEY + ":save",
vm: vm
});
if (vm.rights.delete) {
menuOptions.menuItems.push({
title: vm.$ay.t("ResetToDefault"),
icon: "fa-undo",
surface: false,
key: FORM_KEY + ":delete",
vm: vm
});
}
}
window.$gz.eventBus.$emit("menu-change", menuOptions);
}
/////////////////////////////////
//
//
function initForm(vm) {
return new Promise(function(resolve, reject) {
(async function() {
try {
await fetchTranslatedText(vm);
await populateSelectionLists(vm);
} catch (err) {
reject(err);
}
resolve();
})();
});
}
//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
function fetchTranslatedText(vm) {
let tKeysRequired = ["Include", "ResetToDefault"];
return window.$gz.translation.fetch(tKeysRequired);
}
//////////////////////
//
//
function populateSelectionLists(vm) {
return window.$gz.api.get(API_BASE_URL + "List").then(res => {
if (res.error != undefined) {
window.$gz.errorHandler.handleFormError(res.error, vm);
} else {
vm.selectLists.pickListTemplates = res.data;
window.$gz.form.addNoSelectionItem(vm.selectLists.pickListTemplates);
}
});
}
////////////////////
//
function synthesizeWorkingArray(vm) {
vm.workingArray = [];
if (vm.obj.template == null) {
return;
}
let template = JSON.parse(vm.obj.template);
//first, insert the templated fields into the working array so they are in current selected order
for (let i = 0; i < template.length; i++) {
let templateItem = template[i];
let afItem = window.$gz._.find(vm.availableFields, [
"fieldKey",
templateItem.fld
]);
if (afItem != null) {
//Push into working array
vm.workingArray.push({
key: afItem.fieldKey,
required: afItem.isRowId == true,
include: true,
title: vm.$ay.t(afItem.tKey)
});
}
}
//Now iterate all the available fields and insert the ones that were not in the current template
for (let i = 0; i < vm.availableFields.length; i++) {
let afItem = vm.availableFields[i];
//skip the active column
if (afItem.isActiveColumn == true) {
continue;
}
//is this field already in the template and was added above?
if (window.$gz._.find(template, ["fld", afItem.fieldKey]) != null) {
continue;
}
//Push into working array
vm.workingArray.push({
key: afItem.fieldKey,
required: afItem.isRowId == true,
include: false,
title: vm.$ay.t(afItem.tKey)
});
}
}
</script>