import Vue from 'vue' import api from '@/api' import { DATA_LEVELS, ID_VARIANTS, RELATIONS // FIXME REMOVE WHEN DB MAJ } from '@/store/utils' import { AllNodesOfVariant } from '@/api/queries' export default { state: { nodes: {}, history: [], // IDS ids: { // depart: undefined, // kit: undefined, // creation: undefined } }, mutations: { 'SET_ALL_NODES_IDS' (state, [variant, nodes]) { Vue.set(state.ids, variant, nodes.map(({ id }) => id)) }, 'ADD_NODES' (state, [nodes, dataLevel]) { for (const node of nodes) { const stateNode = node.id in state.nodes ? state.nodes[node.id] : undefined // FIXME UPDATE AFTER DB MAJ if (node.variant === null || Array.isArray(node.variant)) { node.variant = node.variant !== null ? ID_VARIANTS[node.variant[0].id] : 'dark' } if (node.type) { node.type = node.type === 'texte' ? 'ref' : 'prod' } // FIXME REMOVE AFTER DB MAJ for (const relation of RELATIONS) { if (relation in node && node[relation]) { node[relation] = node[relation].map(subNode => { if (!(subNode.id in state.nodes)) { subNode.variant = subNode.variant !== null ? ID_VARIANTS[subNode.variant[0].id] : 'black' subNode.dataLevel = -1 Vue.set(state.nodes, subNode.id, subNode) } return state.nodes[subNode.id] }) } if (node[relation] === null) { node[relation] = [] } } if (!stateNode || stateNode.dataLevel < dataLevel) { node.dataLevel = dataLevel } Vue.set(state.nodes, node.id, stateNode ? { ...stateNode, ...node } : node) } } }, actions: { async 'GET_ALL_NODES_IDS' ({ state, commit }, variant) { if (state.ids[variant] === undefined) { // FIXME UPDATE WHEN QUERY OK // await api.query(AllNodesOfVariant, { variantId: VARIANT_IDS[variant] }).then(data => { await api.query(AllNodesOfVariant).then(data => { commit('SET_ALL_NODES_IDS', [variant, data.nodes]) }) } return state.ids[variant] }, async 'GET_NODES' ({ state, commit, getters }, { ids, dataLevel = 'partial' }) { const lvl = DATA_LEVELS[dataLevel] const nodesIdsToQuery = [] let lowestLvl = lvl for (const id of ids) { const nodeLvl = id in state.nodes ? state.nodes[id].dataLevel : -1 if (nodeLvl < lvl) { nodesIdsToQuery.push(id) } if (nodeLvl < lowestLvl) { lowestLvl = nodeLvl } } if (nodesIdsToQuery.length) { const levelsToQuery = Array(lvl - lowestLvl).fill(lowestLvl + 1).map((v, i) => v + i) await api.queryNodes(nodesIdsToQuery, levelsToQuery).then(data => { commit('ADD_NODES', [data.nodes, lvl]) }) } return getters.nodes(ids) }, async 'GET_NODE' ({ state, commit, getters }, { id, dataLevel = 'full' }) { const lvl = DATA_LEVELS[dataLevel] const nodeLvl = id in state.nodes ? state.nodes[id].dataLevel : -1 if (nodeLvl < lvl) { const levelsToQuery = Array(lvl - nodeLvl).fill(nodeLvl + 1).map((v, i) => v + i) await api.queryNode(id, levelsToQuery).then(data => { commit('ADD_NODES', [[data.node], lvl]) }) } return getters.node(id) } }, getters: { allNodes: state => state.nodes, // Args getters nodes: state => ids => ids.map(id => state.nodes[id]), node: state => id => state.nodes[id] } }