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

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,26 @@
/*
* Utility functions to call bootstrap toasts
* */
import {BToast} from 'bootstrap-vue'
import i18n from "@/i18n";
* Utility functions to call bootstrap toasts
* */
import i18n from "@/i18n"
import { frac } from "@/utils/fractions"
/*
* Utility functions to use OpenAPIs generically
* */
import { ApiApiFactory } from "@/utils/openapi/api.ts"
import axios from "axios"
import { BToast } from "bootstrap-vue"
// /*
// * Utility functions to use manipulate nested components
// * */
import Vue from "vue"
import { Actions, Models } from "./models"
export const ToastMixin = {
methods: {
makeToast: function (title, message, variant = null) {
return makeToast(title, message, variant)
}
}
},
},
}
export function makeToast(title, message, variant = null) {
@@ -17,57 +28,71 @@ export function makeToast(title, message, variant = null) {
toaster.$bvToast.toast(message, {
title: title,
variant: variant,
toaster: 'b-toaster-bottom-right',
solid: true
toaster: "b-toaster-bottom-right",
solid: true,
})
}
export class StandardToasts {
static SUCCESS_CREATE = 'SUCCESS_CREATE'
static SUCCESS_FETCH = 'SUCCESS_FETCH'
static SUCCESS_UPDATE = 'SUCCESS_UPDATE'
static SUCCESS_DELETE = 'SUCCESS_DELETE'
static SUCCESS_CREATE = "SUCCESS_CREATE"
static SUCCESS_FETCH = "SUCCESS_FETCH"
static SUCCESS_UPDATE = "SUCCESS_UPDATE"
static SUCCESS_DELETE = "SUCCESS_DELETE"
static SUCCESS_MOVE = "SUCCESS_MOVE"
static SUCCESS_MERGE = "SUCCESS_MERGE"
static FAIL_CREATE = 'FAIL_CREATE'
static FAIL_FETCH = 'FAIL_FETCH'
static FAIL_UPDATE = 'FAIL_UPDATE'
static FAIL_DELETE = 'FAIL_DELETE'
static FAIL_CREATE = "FAIL_CREATE"
static FAIL_FETCH = "FAIL_FETCH"
static FAIL_UPDATE = "FAIL_UPDATE"
static FAIL_DELETE = "FAIL_DELETE"
static FAIL_MOVE = "FAIL_MOVE"
static FAIL_MERGE = "FAIL_MERGE"
static makeStandardToast(toast) {
static makeStandardToast(toast, err_details = undefined) {
switch (toast) {
case StandardToasts.SUCCESS_CREATE:
makeToast(i18n.tc('Success'), i18n.tc('success_creating_resource'), 'success')
break;
makeToast(i18n.tc("Success"), i18n.tc("success_creating_resource"), "success")
break
case StandardToasts.SUCCESS_FETCH:
makeToast(i18n.tc('Success'), i18n.tc('success_fetching_resource'), 'success')
break;
makeToast(i18n.tc("Success"), i18n.tc("success_fetching_resource"), "success")
break
case StandardToasts.SUCCESS_UPDATE:
makeToast(i18n.tc('Success'), i18n.tc('success_updating_resource'), 'success')
break;
makeToast(i18n.tc("Success"), i18n.tc("success_updating_resource"), "success")
break
case StandardToasts.SUCCESS_DELETE:
makeToast(i18n.tc('Success'), i18n.tc('success_deleting_resource'), 'success')
break;
makeToast(i18n.tc("Success"), i18n.tc("success_deleting_resource"), "success")
break
case StandardToasts.SUCCESS_MOVE:
makeToast(i18n.tc("Success"), i18n.tc("success_moving_resource"), "success")
break
case StandardToasts.SUCCESS_MERGE:
makeToast(i18n.tc("Success"), i18n.tc("success_merging_resource"), "success")
break
case StandardToasts.FAIL_CREATE:
makeToast(i18n.tc('Failure'), i18n.tc('err_creating_resource'), 'danger')
break;
makeToast(i18n.tc("Failure"), i18n.tc("err_creating_resource"), "danger")
break
case StandardToasts.FAIL_FETCH:
makeToast(i18n.tc('Failure'), i18n.tc('err_fetching_resource'), 'danger')
break;
makeToast(i18n.tc("Failure"), i18n.tc("err_fetching_resource"), "danger")
break
case StandardToasts.FAIL_UPDATE:
makeToast(i18n.tc('Failure'), i18n.tc('err_updating_resource'), 'danger')
break;
makeToast(i18n.tc("Failure"), i18n.tc("err_updating_resource"), "danger")
break
case StandardToasts.FAIL_DELETE:
makeToast(i18n.tc('Failure'), i18n.tc('err_deleting_resource'), 'danger')
break;
makeToast(i18n.tc("Failure"), i18n.tc("err_deleting_resource"), "danger")
break
case StandardToasts.FAIL_MOVE:
makeToast(i18n.tc("Failure"), i18n.tc("err_moving_resource") + (err_details ? "\n" + err_details : ""), "danger")
break
case StandardToasts.FAIL_MERGE:
makeToast(i18n.tc("Failure"), i18n.tc("err_merging_resource") + (err_details ? "\n" + err_details : ""), "danger")
break
}
}
}
/*
* Utility functions to use djangos gettext
* */
* Utility functions to use djangos gettext
* */
export const GettextMixin = {
methods: {
@@ -77,8 +102,8 @@ export const GettextMixin = {
*/
_: function (param) {
return djangoGettext(param)
}
}
},
},
}
export function djangoGettext(param) {
@@ -86,8 +111,8 @@ export function djangoGettext(param) {
}
/*
* Utility function to use djangos named urls
* */
* Utility function to use djangos named urls
* */
// uses https://github.com/ierror/django-js-reverse#use-the-urls-in-javascript
export const ResolveUrlMixin = {
@@ -99,50 +124,48 @@ export const ResolveUrlMixin = {
*/
resolveDjangoUrl: function (url, params = null) {
return resolveDjangoUrl(url, params)
}
}
},
},
}
export function resolveDjangoUrl(url, params = null) {
if (params == null) {
return window.Urls[url]()
} else if (typeof(params) != "object") {
} else if (typeof params != "object") {
return window.Urls[url](params)
} else if (typeof(params) == "object") {
} else if (typeof params == "object") {
if (params.length === 1) {
return window.Urls[url](params)
} else if (params.length === 2) {
return window.Urls[url](params[0],params[1])
return window.Urls[url](params[0], params[1])
} else if (params.length === 3) {
return window.Urls[url](params[0],params[1],params[2])
return window.Urls[url](params[0], params[1], params[2])
}
}
}
/*
* other utilities
* */
* other utilities
* */
export function getUserPreference(pref) {
if(window.USER_PREF === undefined) {
return undefined;
if (window.USER_PREF === undefined) {
return undefined
}
return window.USER_PREF[pref]
}
import {frac} from "@/utils/fractions";
export function calculateAmount(amount, factor) {
if (getUserPreference('use_fractions')) {
let return_string = ''
let fraction = frac((amount * factor), 10, true)
if (getUserPreference("use_fractions")) {
let return_string = ""
let fraction = frac(amount * factor, 10, true)
if (fraction[0] > 0) {
return_string += fraction[0]
}
if (fraction[1] > 0) {
return_string += ` <sup>${(fraction[1])}</sup>&frasl;<sub>${(fraction[2])}</sub>`
return_string += ` <sup>${fraction[1]}</sup>&frasl;<sub>${fraction[2]}</sub>`
}
return return_string
@@ -152,23 +175,23 @@ export function calculateAmount(amount, factor) {
}
export function roundDecimals(num) {
let decimals = ((getUserPreference('user_fractions')) ? getUserPreference('user_fractions') : 2);
return +(Math.round(num + `e+${decimals}`) + `e-${decimals}`);
let decimals = getUserPreference("user_fractions") ? getUserPreference("user_fractions") : 2
return +(Math.round(num + `e+${decimals}`) + `e-${decimals}`)
}
const KILOJOULES_PER_CALORIE = 4.18
export function calculateEnergy(amount, factor) {
if (getUserPreference('use_kj')) {
if (getUserPreference("use_kj")) {
let joules = amount * KILOJOULES_PER_CALORIE
return calculateAmount(joules, factor) + ' kJ'
return calculateAmount(joules, factor) + " kJ"
} else {
return calculateAmount(amount, factor) + ' kcal'
return calculateAmount(amount, factor) + " kcal"
}
}
export function convertEnergyToCalories(amount) {
if (getUserPreference('use_kj')) {
if (getUserPreference("use_kj")) {
return amount / KILOJOULES_PER_CALORIE
} else {
return amount
@@ -176,33 +199,25 @@ export function convertEnergyToCalories(amount) {
}
export function energyHeading() {
if (getUserPreference('use_kj')) {
return 'Energy'
if (getUserPreference("use_kj")) {
return "Energy"
} else {
return 'Calories'
return "Calories"
}
}
/*
* Utility functions to use OpenAPIs generically
* */
import {ApiApiFactory} from "@/utils/openapi/api.ts";
import axios from "axios";
axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfCookieName = "csrftoken"
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"
import { Actions, Models } from './models';
import {RequestArgs} from "@/utils/openapi/base";
export const ApiMixin = {
data() {
return {
Models: Models,
Actions: Actions
Actions: Actions,
}
},
methods: {
genericAPI: function(model, action, options) {
genericAPI: function (model, action, options) {
let setup = getConfig(model, action)
if (setup?.config?.function) {
return specialCases[setup.config.function](action, options, setup)
@@ -212,10 +227,10 @@ export const ApiMixin = {
let apiClient = new ApiApiFactory()
return apiClient[func](...parameters)
},
genericGetAPI: function(url, options) {
return axios.get(this.resolveDjangoUrl(url), {'params':options, 'emulateJSON': true})
}
}
genericGetAPI: function (url, options) {
return axios.get(this.resolveDjangoUrl(url), { params: options, emulateJSON: true })
},
},
}
// /*
@@ -223,37 +238,37 @@ export const ApiMixin = {
// * */
function formatParam(config, value, options) {
if (config) {
for (const [k, v] of Object.entries(config)) {
switch(k) {
case 'type':
switch(v) {
case 'string':
for (const [k, v] of Object.entries(config)) {
switch (k) {
case "type":
switch (v) {
case "string":
if (Array.isArray(value)) {
let tmpValue = []
value.forEach(x => tmpValue.push(String(x)))
value.forEach((x) => tmpValue.push(String(x)))
value = tmpValue
} else if (value !== undefined) {
value = String(value)
}
break;
case 'integer':
break
case "integer":
if (Array.isArray(value)) {
let tmpValue = []
value.forEach(x => tmpValue.push(parseInt(x)))
value.forEach((x) => tmpValue.push(parseInt(x)))
value = tmpValue
} else if (value !== undefined) {
value = parseInt(value)
}
break;
break
}
break;
case 'function':
break
case "function":
// needs wrapped in a promise and wait for the called function to complete before moving on
specialCases[v](value, options)
break;
break
}
}
}
}
return value
}
function buildParams(options, setup) {
@@ -280,60 +295,56 @@ function buildParams(options, setup) {
this_value = getDefault(config?.[item], options)
}
parameters.push(this_value)
});
})
return parameters
}
function getDefault(config, options) {
let value = undefined
value = config?.default ?? undefined
if (typeof(value) === 'object') {
if (typeof value === "object") {
let condition = false
switch(value.function) {
switch (value.function) {
// CONDITIONAL case requires 4 keys:
// - check: which other OPTIONS key to check against
// - operator: what type of operation to perform
// - true: what value to assign when true
// - false: what value to assign when false
case 'CONDITIONAL':
switch(value.operator) {
case 'not_exist':
condition = (
(!options?.[value.check] ?? undefined)
|| options?.[value.check]?.length == 0
)
case "CONDITIONAL":
switch (value.operator) {
case "not_exist":
condition = (!options?.[value.check] ?? undefined) || options?.[value.check]?.length == 0
if (condition) {
value = value.true
} else {
value = value.false
}
break;
break
}
break;
break
}
}
return value
}
export function getConfig(model, action) {
let f = action.function
// if not defined partialUpdate will use params from create
if (f === 'partialUpdate' && !model?.[f]?.params) {
model[f] = {'params': [...['id'], ...model.create.params]}
if (f === "partialUpdate" && !model?.[f]?.params) {
model[f] = { params: [...["id"], ...model.create.params] }
}
let config = {
'name': model.name,
'apiName': model.apiName,
name: model.name,
apiName: model.apiName,
}
// spread operator merges dictionaries - last item in list takes precedence
config = {...config, ...action, ...model.model_type?.[f], ...model?.[f]}
config = { ...config, ...action, ...model.model_type?.[f], ...model?.[f] }
// nested dictionaries are not merged - so merge again on any nested keys
config.config = {...action?.config, ...model.model_type?.[f]?.config, ...model?.[f]?.config}
config.config = { ...action?.config, ...model.model_type?.[f]?.config, ...model?.[f]?.config }
// look in partialUpdate again if necessary
if (f === 'partialUpdate' && Object.keys(config.config).length === 0) {
config.config = {...model.model_type?.create?.config, ...model?.create?.config}
if (f === "partialUpdate" && Object.keys(config.config).length === 0) {
config.config = { ...model.model_type?.create?.config, ...model?.create?.config }
}
config['function'] = f + config.apiName + (config?.suffix ?? '') // parens are required to force optional chaining to evaluate before concat
config["function"] = f + config.apiName + (config?.suffix ?? "") // parens are required to force optional chaining to evaluate before concat
return config
}
@@ -342,181 +353,175 @@ export function getConfig(model, action) {
// * */
export function getForm(model, action, item1, item2) {
let f = action.function
let config = {...action?.form, ...model.model_type?.[f]?.form, ...model?.[f]?.form}
// if not defined partialUpdate will use form from create
if (f === 'partialUpdate' && Object.keys(config).length == 0) {
config = {...Actions.CREATE?.form, ...model.model_type?.['create']?.form, ...model?.['create']?.form}
config['title'] = {...action?.form_title, ...model.model_type?.[f]?.form_title, ...model?.[f]?.form_title}
let config = { ...action?.form, ...model.model_type?.[f]?.form, ...model?.[f]?.form }
// if not defined partialUpdate will use form from create
if (f === "partialUpdate" && Object.keys(config).length == 0) {
config = { ...Actions.CREATE?.form, ...model.model_type?.["create"]?.form, ...model?.["create"]?.form }
config["title"] = { ...action?.form_title, ...model.model_type?.[f]?.form_title, ...model?.[f]?.form_title }
}
let form = {'fields': []}
let value = ''
let form = { fields: [] }
let value = ""
for (const [k, v] of Object.entries(config)) {
if (v?.function){
switch(v.function) {
case 'translate':
if (v?.function) {
switch (v.function) {
case "translate":
value = formTranslate(v, model, item1, item2)
}
} else {
value = v
}
if (value?.form_field) {
value['value'] = item1?.[value?.field] ?? undefined
form.fields.push(
{
...value,
...{
'label': formTranslate(value?.label, model, item1, item2),
'placeholder': formTranslate(value?.placeholder, model, item1, item2)
}
}
)
value["value"] = item1?.[value?.field] ?? undefined
form.fields.push({
...value,
...{
label: formTranslate(value?.label, model, item1, item2),
placeholder: formTranslate(value?.placeholder, model, item1, item2),
},
})
} else {
form[k] = value
}
}
return form
}
function formTranslate(translate, model, item1, item2) {
if (typeof(translate) !== 'object') {return translate}
if (typeof translate !== "object") {
return translate
}
let phrase = translate.phrase
let options = {}
let obj = undefined
translate?.params.forEach(function (x, index) {
switch(x.from){
case 'item1':
switch (x.from) {
case "item1":
obj = item1
break;
case 'item2':
break
case "item2":
obj = item2
break;
case 'model':
break
case "model":
obj = model
}
options[x.token] = obj[x.attribute]
})
return i18n.t(phrase, options)
}
// /*
// * Utility functions to use manipulate nested components
// * */
import Vue from 'vue'
export const CardMixin = {
methods: {
findCard: function(id, card_list){
findCard: function (id, card_list) {
let card_length = card_list?.length ?? 0
if (card_length == 0) {
return false
return false
}
let cards = card_list.filter(obj => obj.id == id)
let cards = card_list.filter((obj) => obj.id == id)
if (cards.length == 1) {
return cards[0]
return cards[0]
} else if (cards.length == 0) {
for (const c of card_list.filter(x => x.show_children == true)) {
cards = this.findCard(id, c.children)
if (cards) {
return cards
for (const c of card_list.filter((x) => x.show_children == true)) {
cards = this.findCard(id, c.children)
if (cards) {
return cards
}
}
}
} else {
console.log('something terrible happened')
console.log("something terrible happened")
}
},
destroyCard: function(id, card_list) {
destroyCard: function (id, card_list) {
let card = this.findCard(id, card_list)
let p_id = card?.parent ?? undefined
if (p_id) {
let parent = this.findCard(p_id, card_list)
if (parent){
Vue.set(parent, 'numchild', parent.numchild - 1)
if (parent) {
Vue.set(parent, "numchild", parent.numchild - 1)
if (parent.show_children) {
let idx = parent.children.indexOf(parent.children.find(x => x.id === id))
let idx = parent.children.indexOf(parent.children.find((x) => x.id === id))
Vue.delete(parent.children, idx)
}
}
}
return card_list.filter(x => x.id != id)
},
refreshCard: function(obj, card_list){
return card_list.filter((x) => x.id != id)
},
refreshCard: function (obj, card_list) {
let target = {}
let idx = undefined
target = this.findCard(obj.id, card_list)
if (target) {
idx = card_list.indexOf(card_list.find(x => x.id === target.id))
idx = card_list.indexOf(card_list.find((x) => x.id === target.id))
Vue.set(card_list, idx, obj)
}
if (target?.parent) {
let parent = this.findCard(target.parent, card_list)
if (parent) {
if (parent.show_children){
idx = parent.children.indexOf(parent.children.find(x => x.id === target.id))
if (parent.show_children) {
idx = parent.children.indexOf(parent.children.find((x) => x.id === target.id))
Vue.set(parent.children, idx, obj)
}
}
}
},
}
},
}
const specialCases = {
// the supermarket API requires chaining promises together, instead of trying to make
// this use case generic just treat it as a unique use case
SupermarketWithCategories: function(action, options, setup) {
SupermarketWithCategories: function (action, options, setup) {
let API = undefined
let GenericAPI = ApiMixin.methods.genericAPI
let params = []
if (action.function === 'partialUpdate') {
if (action.function === "partialUpdate") {
API = GenericAPI
params = [Models.SUPERMARKET, Actions.FETCH, {'id': options.id}]
} else if (action.function === 'create') {
params = [Models.SUPERMARKET, Actions.FETCH, { id: options.id }]
} else if (action.function === "create") {
API = new ApiApiFactory()[setup.function]
params = buildParams(options, setup)
}
return API(...params).then((result) => {
// either get the supermarket or create the supermarket (but without the category relations)
return result.data
}).then((result) => {
// delete, update or change all of the category/relations
let id = result.id
let existing_categories = result.category_to_supermarket
let updated_categories = options.category_to_supermarket
let promises = []
// if the 'category.name' key does not exist on the updated_categories, the categories were not updated
if (updated_categories?.[0]?.category?.name) {
// list of category relationship ids that are not part of the updated supermarket
let removed_categories = existing_categories.filter(x => !updated_categories.map(x => x.category.id).includes(x.category.id))
let added_categories = updated_categories.filter(x => !existing_categories.map(x => x.category.id).includes(x.category.id))
let changed_categories = updated_categories.filter(x => existing_categories.map(x => x.category.id).includes(x.category.id))
removed_categories.forEach(x => {
promises.push(GenericAPI(Models.SHOPPING_CATEGORY_RELATION, Actions.DELETE, {'id': x.id}))
})
let item = {'supermarket': id}
added_categories.forEach(x => {
item.order = x.order
item.category = {'id': x.category.id, 'name': x.category.name}
promises.push(GenericAPI(Models.SHOPPING_CATEGORY_RELATION, Actions.CREATE, item))
})
changed_categories.forEach(x => {
item.id = x?.id ?? existing_categories.find(y => y.category.id === x.category.id).id;
item.order = x.order
item.category = {'id': x.category.id, 'name': x.category.name}
promises.push(GenericAPI(Models.SHOPPING_CATEGORY_RELATION, Actions.UPDATE, item))
})
}
return Promise.all(promises).then(() => {
// finally get and return the Supermarket which everything downstream is expecting
return GenericAPI(Models.SUPERMARKET, Actions.FETCH, {'id': id})
return API(...params)
.then((result) => {
// either get the supermarket or create the supermarket (but without the category relations)
return result.data
})
})
}
.then((result) => {
// delete, update or change all of the category/relations
let id = result.id
let existing_categories = result.category_to_supermarket
let updated_categories = options.category_to_supermarket
let promises = []
// if the 'category.name' key does not exist on the updated_categories, the categories were not updated
if (updated_categories?.[0]?.category?.name) {
// list of category relationship ids that are not part of the updated supermarket
let removed_categories = existing_categories.filter((x) => !updated_categories.map((x) => x.category.id).includes(x.category.id))
let added_categories = updated_categories.filter((x) => !existing_categories.map((x) => x.category.id).includes(x.category.id))
let changed_categories = updated_categories.filter((x) => existing_categories.map((x) => x.category.id).includes(x.category.id))
removed_categories.forEach((x) => {
promises.push(GenericAPI(Models.SHOPPING_CATEGORY_RELATION, Actions.DELETE, { id: x.id }))
})
let item = { supermarket: id }
added_categories.forEach((x) => {
item.order = x.order
item.category = { id: x.category.id, name: x.category.name }
promises.push(GenericAPI(Models.SHOPPING_CATEGORY_RELATION, Actions.CREATE, item))
})
changed_categories.forEach((x) => {
item.id = x?.id ?? existing_categories.find((y) => y.category.id === x.category.id).id
item.order = x.order
item.category = { id: x.category.id, name: x.category.name }
promises.push(GenericAPI(Models.SHOPPING_CATEGORY_RELATION, Actions.UPDATE, item))
})
}
return Promise.all(promises).then(() => {
// finally get and return the Supermarket which everything downstream is expecting
return GenericAPI(Models.SUPERMARKET, Actions.FETCH, { id: id })
})
})
},
}