generic modal refactored

This commit is contained in:
smilerz
2021-11-23 19:18:10 -06:00
parent 3fe5340592
commit 5b6dd62f8e
17 changed files with 1951 additions and 1805 deletions

View File

@ -1,143 +1,250 @@
<template>
<div>
<b-modal :id="'modal_'+id" @hidden="cancelAction">
<template v-slot:modal-title><h4>{{ form.title }}</h4></template>
<div v-for="(f, i) in form.fields" v-bind:key=i>
<p v-if="f.type=='instruction'">{{ f.label }}</p>
<!-- this lookup is single selection -->
<lookup-input v-if="f.type=='lookup'"
:form="f"
:model="listModel(f.list)"
@change="storeValue"/> <!-- TODO add ability to create new items associated with lookup -->
<!-- TODO: add multi-selection input list -->
<checkbox-input v-if="f.type=='checkbox'"
:label="f.label"
:value="f.value"
:field="f.field"/>
<text-input v-if="f.type=='text'"
:label="f.label"
:value="f.value"
:field="f.field"
:placeholder="f.placeholder"/>
<choice-input v-if="f.type=='choice'"
:label="f.label"
:value="f.value"
:field="f.field"
:options="f.options"
:placeholder="f.placeholder"/>
<emoji-input v-if="f.type=='emoji'"
:label="f.label"
:value="f.value"
:field="f.field"
@change="storeValue"/>
<file-input v-if="f.type=='file'"
:label="f.label"
:value="f.value"
:field="f.field"
@change="storeValue"/>
</div>
<div>
<b-modal :id="'modal_' + id" @hidden="cancelAction">
<template v-slot:modal-title
><h4>{{ form.title }}</h4></template
>
<div v-for="(f, i) in form.fields" v-bind:key="i">
<p v-if="f.type == 'instruction'">{{ f.label }}</p>
<!-- this lookup is single selection -->
<lookup-input v-if="f.type == 'lookup'" :form="f" :model="listModel(f.list)" @change="storeValue" />
<!-- TODO add ability to create new items associated with lookup -->
<!-- TODO: add multi-selection input list -->
<checkbox-input v-if="f.type == 'checkbox'" :label="f.label" :value="f.value" :field="f.field" />
<text-input v-if="f.type == 'text'" :label="f.label" :value="f.value" :field="f.field" :placeholder="f.placeholder" />
<choice-input v-if="f.type == 'choice'" :label="f.label" :value="f.value" :field="f.field" :options="f.options" :placeholder="f.placeholder" />
<emoji-input v-if="f.type == 'emoji'" :label="f.label" :value="f.value" :field="f.field" @change="storeValue" />
<file-input v-if="f.type == 'file'" :label="f.label" :value="f.value" :field="f.field" @change="storeValue" />
</div>
<template v-slot:modal-footer>
<b-button class="float-right mx-1" variant="secondary" v-on:click="cancelAction">{{ $t('Cancel') }}</b-button>
<b-button class="float-right mx-1" variant="primary" v-on:click="doAction">{{ form.ok_label }}</b-button>
</template>
</b-modal>
</div>
<template v-slot:modal-footer>
<b-button class="float-right mx-1" variant="secondary" v-on:click="cancelAction">{{ $t("Cancel") }}</b-button>
<b-button class="float-right mx-1" variant="primary" v-on:click="doAction">{{ form.ok_label }}</b-button>
</template>
</b-modal>
</div>
</template>
<script>
import Vue from 'vue'
import {BootstrapVue} from 'bootstrap-vue'
import {getForm} from "@/utils/utils";
import Vue from "vue"
import { BootstrapVue } from "bootstrap-vue"
import { getForm } from "@/utils/utils"
Vue.use(BootstrapVue)
import {Models} from "@/utils/models";
import CheckboxInput from "@/components/Modals/CheckboxInput";
import LookupInput from "@/components/Modals/LookupInput";
import TextInput from "@/components/Modals/TextInput";
import EmojiInput from "@/components/Modals/EmojiInput";
import ChoiceInput from "@/components/Modals/ChoiceInput";
import FileInput from "@/components/Modals/FileInput";
import { ApiApiFactory } from "@/utils/openapi/api"
import { ApiMixin, StandardToasts, ToastMixin } from "@/utils/utils"
import CheckboxInput from "@/components/Modals/CheckboxInput"
import LookupInput from "@/components/Modals/LookupInput"
import TextInput from "@/components/Modals/TextInput"
import EmojiInput from "@/components/Modals/EmojiInput"
import ChoiceInput from "@/components/Modals/ChoiceInput"
import FileInput from "@/components/Modals/FileInput"
export default {
name: 'GenericModalForm',
components: {FileInput, CheckboxInput, LookupInput, TextInput, EmojiInput, ChoiceInput},
props: {
model: {required: true, type: Object},
action: {required: true, type: Object},
item1: {
type: Object, default() {
return undefined
}
name: "GenericModalForm",
components: { FileInput, CheckboxInput, LookupInput, TextInput, EmojiInput, ChoiceInput },
mixins: [ApiMixin, ToastMixin],
props: {
model: { required: true, type: Object },
action: { type: Object },
item1: {
type: Object,
default() {
return {}
},
},
item2: {
type: Object,
default() {
return {}
},
},
show: { required: true, type: Boolean, default: false },
},
item2: {
type: Object, default() {
return undefined
}
},
show: {required: true, type: Boolean, default: false},
},
data() {
return {
id: undefined,
form_data: {},
form: {},
dirty: false,
special_handling: false
}
},
mounted() {
this.id = Math.random()
this.$root.$on('change', this.storeValue); // boostrap modal placed at document so have to listen at root of component
},
computed: {
buttonLabel() {
return this.buttons[this.action].label;
},
},
watch: {
'show': function () {
if (this.show) {
this.form = getForm(this.model, this.action, this.item1, this.item2)
this.dirty = true
this.$bvModal.show('modal_' + this.id)
} else {
this.$bvModal.hide('modal_' + this.id)
this.form_data = {}
}
},
},
methods: {
doAction: function () {
this.dirty = false
this.$emit('finish-action', {'form_data': this.detectOverride(this.form_data)})
},
cancelAction: function () {
if (this.dirty) {
this.dirty = false
this.$emit('finish-action', 'cancel')
}
},
storeValue: function (field, value) {
this.form_data[field] = value
},
listModel: function (m) {
if (m === 'self') {
return this.model
} else {
return Models[m]
}
},
detectOverride: function (form) {
for (const [k, v] of Object.entries(form)) {
if (form[k].__override__) {
form[k] = form[k].__override__
data() {
return {
id: undefined,
form_data: {},
form: {},
dirty: false,
special_handling: false,
}
}
return form
}
}
},
mounted() {
this.id = Math.random()
this.$root.$on("change", this.storeValue) // boostrap modal placed at document so have to listen at root of component
},
computed: {
buttonLabel() {
return this.buttons[this.action].label
},
},
watch: {
show: function () {
if (this.show) {
this.form = getForm(this.model, this.action, this.item1, this.item2)
this.dirty = true
this.$bvModal.show("modal_" + this.id)
} else {
this.$bvModal.hide("modal_" + this.id)
this.form_data = {}
}
},
},
methods: {
doAction: function () {
this.dirty = false
switch (this.action) {
case this.Actions.DELETE:
this.delete()
break
case this.Actions.CREATE:
this.save()
break
case this.Actions.UPDATE:
this.form_data.id = this.item1.id
this.save()
break
case this.Actions.MERGE:
this.merge(this.item1, this.form_data.target.id, this.item1?.automate ?? false)
break
case this.Actions.MOVE:
this.move(this.item1.id, this.form_data.target.id)
break
}
},
cancelAction: function () {
if (this.dirty) {
this.dirty = false
this.$emit("finish-action", "cancel")
}
},
storeValue: function (field, value) {
this.form_data[field] = value
},
listModel: function (m) {
if (m === "self") {
return this.model
} else {
return this.Models[m]
}
},
detectOverride: function (form) {
for (const [k, v] of Object.entries(form)) {
if (form[k].__override__) {
form[k] = form[k].__override__
}
}
return form
},
delete: function () {
this.genericAPI(this.model, this.Actions.DELETE, { id: this.item1.id })
.then((result) => {
this.$emit("finish-action")
StandardToasts.makeStandardToast(StandardToasts.SUCCESS_DELETE)
})
.catch((err) => {
console.log(err)
StandardToasts.makeStandardToast(StandardToasts.FAIL_DELETE)
this.$emit("finish-action", "cancel")
})
},
save: function () {
if (!this.item1?.id) {
// if there is no item id assume it's a new item
this.genericAPI(this.model, this.Actions.CREATE, this.form_data)
.then((result) => {
this.$emit("finish-action", { item: result.data })
StandardToasts.makeStandardToast(StandardToasts.SUCCESS_CREATE)
})
.catch((err) => {
console.log(err)
StandardToasts.makeStandardToast(StandardToasts.FAIL_CREATE)
this.$emit("finish-action", "cancel")
})
} else {
this.genericAPI(this.model, this.Actions.UPDATE, this.form_data)
.then((result) => {
this.$emit("finish-action")
StandardToasts.makeStandardToast(StandardToasts.SUCCESS_UPDATE)
})
.catch((err) => {
console.log(err, err.response)
StandardToasts.makeStandardToast(StandardToasts.FAIL_UPDATE)
this.$emit("finish-action", "cancel")
})
}
},
move: function () {
if (this.item1.id === this.form_data.target.id) {
this.makeToast(this.$t("Error"), this.$t("err_move_self"), "danger")
this.$emit("finish-action", "cancel")
return
}
if (this.form_data.target.id === undefined || this.item1?.parent == this.form_data.target.id) {
this.makeToast(this.$t("Warning"), this.$t("nothing"), "warning")
this.$emit("finish-action", "cancel")
return
}
this.genericAPI(this.model, this.Actions.MOVE, { source: this.item1.id, target: this.form_data.target.id })
.then((result) => {
this.$emit("finish-action", { target: this.form_data.target.id })
StandardToasts.makeStandardToast(StandardToasts.SUCCESS_MOVE)
})
.catch((err) => {
console.log(err)
StandardToasts.makeStandardToast(StandardToasts.FAIL_MOVE)
this.$emit("finish-action", "cancel")
})
},
merge: function () {
if (this.item1.id === this.form_data.target.id) {
this.makeToast(this.$t("Error"), this.$t("err_merge_self"), "danger")
this.$emit("finish-action", "cancel")
return
}
if (!this.item1.id || !this.form_data.target.id) {
this.makeToast(this.$t("Warning"), this.$t("nothing"), "warning")
this.$emit("finish-action", "cancel")
return
}
this.genericAPI(this.model, this.Actions.MERGE, {
source: this.item1.id,
target: this.form_data.target.id,
})
.then((result) => {
this.$emit("finish-action", { target: this.form_data.target.id })
StandardToasts.makeStandardToast(StandardToasts.SUCCESS_MERGE)
})
.catch((err) => {
//TODO error checking not working with OpenAPI methods
console.log("Error", err)
StandardToasts.makeStandardToast(StandardToasts.FAIL_MERGE)
this.$emit("finish-action", "cancel")
})
if (this.item1.automate) {
let apiClient = new ApiApiFactory()
let automation = {
name: `Merge ${this.item1.name} with ${this.form_data.target.name}`,
param_1: this.item1.name,
param_2: this.form_data.target.name,
}
if (this.model === this.Models.FOOD) {
automation.type = "FOOD_ALIAS"
}
if (this.model === this.Models.UNIT) {
automation.type = "UNIT_ALIAS"
}
if (this.model === this.Models.KEYWORD) {
automation.type = "KEYWORD_ALIAS"
}
apiClient.createAutomation(automation)
}
},
},
}
</script>
</script>

View File

@ -1,157 +1,171 @@
<template>
<div>
<b-form-group
v-bind:label="form.label"
class="mb-3">
<generic-multiselect
@change="new_value=$event.val"
@remove="new_value=undefined"
:initial_selection="initialSelection"
:model="model"
:multiple="useMultiple"
:sticky_options="sticky_options"
:allow_create="create_new"
:create_placeholder="createPlaceholder"
style="flex-grow: 1; flex-shrink: 1; flex-basis: 0"
:placeholder="modelName"
@new="addNew">
</generic-multiselect>
<b-form-group class="mb-3">
<template #label v-if="show_label">
{{ form.label }}
</template>
<generic-multiselect
@change="new_value = $event.val"
@remove="new_value = undefined"
:initial_selection="initialSelection"
:model="model"
:multiple="useMultiple"
:sticky_options="sticky_options"
:allow_create="form.allow_create"
:create_placeholder="createPlaceholder"
style="flex-grow: 1; flex-shrink: 1; flex-basis: 0"
:placeholder="modelName"
@new="addNew"
>
</generic-multiselect>
</b-form-group>
</div>
</template>
<script>
import GenericMultiselect from "@/components/GenericMultiselect";
import {StandardToasts, ApiMixin} from "@/utils/utils";
import GenericMultiselect from "@/components/GenericMultiselect"
import { StandardToasts, ApiMixin } from "@/utils/utils"
export default {
name: 'LookupInput',
components: {GenericMultiselect},
mixins: [ApiMixin],
props: {
form: {type: Object, default () {return undefined}},
model: {type: Object, default () {return undefined}},
// TODO: include create_new and create_text props and associated functionality to create objects for drop down
// see 'tagging' here: https://vue-multiselect.js.org/#sub-tagging
// perfect world would have it trigger a new modal associated with the associated item model
},
data() {
return {
new_value: undefined,
field: undefined,
label: undefined,
sticky_options: undefined,
first_run: true
}
},
mounted() {
this.new_value = this.form?.value
this.field = this.form?.field ?? 'You Forgot To Set Field Name'
this.label = this.form?.label ?? ''
this.sticky_options = this.form?.sticky_options ?? []
},
computed: {
modelName() {
return this?.model?.name ?? this.$t('Search')
name: "LookupInput",
components: { GenericMultiselect },
mixins: [ApiMixin],
props: {
form: {
type: Object,
default() {
return undefined
},
},
model: {
type: Object,
default() {
return undefined
},
},
show_label: { type: Boolean, default: true },
},
useMultiple() {
return this.form?.multiple || this.form?.ordered || false
},
initialSelection() {
let this_value = this.form.value
let arrayValues = undefined
// multiselect is expect to get an array of objects - make sure it gets one
if (Array.isArray(this_value)) {
arrayValues = this_value
} else if (!this_value) {
arrayValues = []
} else if (typeof(this_value) === 'object') {
arrayValues = [this_value]
} else {
arrayValues = [{'id': -1, 'name': this_value}]
}
if (this.form?.ordered && this.first_run) {
return this.flattenItems(arrayValues)
} else {
return arrayValues
}
},
createPlaceholder() {
return this.$t('Create_New_' + this?.model?.name)
}
},
watch: {
'new_value': function () {
let x = this?.new_value
// pass the unflattened attributes that can be restored when ready to save/update
if (this.form?.ordered) {
x['__override__'] = this.unflattenItem(this?.new_value)
}
this.$root.$emit('change', this.form.field, x)
},
},
methods: {
addNew: function(e) {
// if create a new item requires more than 1 parameter or the field 'name' is insufficient this will need reworked
// in a perfect world this would trigger a new modal and allow editing all fields
this.genericAPI(this.model, this.Actions.CREATE, {'name': e}).then((result) => {
this.new_value = result.data
StandardToasts.makeStandardToast(StandardToasts.SUCCESS_CREATE)
}).catch((err) => {
console.log(err)
StandardToasts.makeStandardToast(StandardToasts.FAIL_CREATE)
})
},
// ordered lookups have nested attributes that need flattened attributes to drive lookup
flattenItems: function(itemlist) {
let flat_items = []
let item = undefined
let label = this.form.list_label.split('::')
itemlist.forEach(x => {
item = {}
for (const [k, v] of Object.entries(x)) {
if (k == label[0]) {
item['id'] = v.id
item[label[1]] = v[label[1]]
} else {
item[this.form.field + '__' + k] = v
}
data() {
return {
new_value: undefined,
field: undefined,
label: undefined,
sticky_options: undefined,
first_run: true,
}
flat_items.push(item)
});
this.first_run = false
return flat_items
},
unflattenItem: function(itemList) {
let unflat_items = []
let item = undefined
let this_label = undefined
let label = this.form.list_label.split('::')
let order = 0
itemList.forEach(x => {
item = {}
item[label[0]] = {}
for (const [k, v] of Object.entries(x)) {
switch(k) {
case 'id':
item[label[0]]['id'] = v
break;
case label[1]:
item[label[0]][label[1]] = v
break;
default:
this_label = k.replace(this.form.field + '__', '')
}
}
item['order'] = order
order++
unflat_items.push(item)
});
return unflat_items
}
}
mounted() {
this.new_value = this.form?.value
this.field = this.form?.field ?? "You Forgot To Set Field Name"
this.label = this.form?.label ?? ""
this.sticky_options = this.form?.sticky_options ?? []
},
computed: {
modelName() {
return this?.model?.name ?? this.$t("Search")
},
useMultiple() {
return this.form?.multiple || this.form?.ordered || false
},
initialSelection() {
let this_value = this.new_value
let arrayValues = undefined
// multiselect is expect to get an array of objects - make sure it gets one
if (Array.isArray(this_value)) {
arrayValues = this_value
} else if (!this_value) {
arrayValues = []
} else if (typeof this_value === "object") {
arrayValues = [this_value]
} else {
arrayValues = [{ id: -1, name: this_value }]
}
if (this.form?.ordered && this.first_run) {
return this.flattenItems(arrayValues)
} else {
return arrayValues
}
},
createPlaceholder() {
return this.$t("Create_New_" + this?.model?.name)
},
},
watch: {
"form.value": function (newVal, oldVal) {
this.new_value = newVal
},
new_value: function () {
let x = this?.new_value
// pass the unflattened attributes that can be restored when ready to save/update
if (this.form?.ordered) {
x["__override__"] = this.unflattenItem(this?.new_value)
}
this.$root.$emit("change", this.form.field, x)
this.$emit("change", x)
},
},
methods: {
addNew: function (e) {
// if create a new item requires more than 1 parameter or the field 'name' is insufficient this will need reworked
// in a perfect world this would trigger a new modal and allow editing all fields
this.genericAPI(this.model, this.Actions.CREATE, { name: e })
.then((result) => {
this.new_value = result.data
StandardToasts.makeStandardToast(StandardToasts.SUCCESS_CREATE)
})
.catch((err) => {
console.log(err)
StandardToasts.makeStandardToast(StandardToasts.FAIL_CREATE)
})
},
// ordered lookups have nested attributes that need flattened attributes to drive lookup
flattenItems: function (itemlist) {
let flat_items = []
let item = undefined
let label = this.form.list_label.split("::")
itemlist.forEach((x) => {
item = {}
for (const [k, v] of Object.entries(x)) {
if (k == label[0]) {
item["id"] = v.id
item[label[1]] = v[label[1]]
} else {
item[this.form.field + "__" + k] = v
}
}
flat_items.push(item)
})
this.first_run = false
return flat_items
},
unflattenItem: function (itemList) {
let unflat_items = []
let item = undefined
let this_label = undefined
let label = this.form.list_label.split("::")
let order = 0
itemList.forEach((x) => {
item = {}
item[label[0]] = {}
for (const [k, v] of Object.entries(x)) {
switch (k) {
case "id":
item[label[0]]["id"] = v
break
case label[1]:
item[label[0]][label[1]] = v
break
default:
this_label = k.replace(this.form.field + "__", "")
}
}
item["order"] = order
order++
unflat_items.push(item)
})
return unflat_items
},
},
}
</script>
</script>