diff --git a/src/store/client-fields.js b/src/store/client-fields.js index 390f7fd..0429cf4 100644 --- a/src/store/client-fields.js +++ b/src/store/client-fields.js @@ -23,6 +23,20 @@ export default { client_id: clientId, }); }, + async addAllFields(store, clientId) { + // Get all distinct custom fields + const uniqueLabels = ClientField.all() + .map(field => field.label) + .filter((value, index, self) => self.indexOf(value) === index); + + await Promise.all(uniqueLabels.map(async (label) => { + const field = await ClientField.createNew(); + await field.$update({ + label, + client_id: clientId, + }); + })); + }, async deleteClientField({ dispatch }, fieldId) { await ClientField.delete(fieldId); return dispatch('clients/updateClient', null, { root: true }); // TODO: pass clientId to make generic diff --git a/src/store/clients.js b/src/store/clients.js index b506e40..ab0b5f4 100644 --- a/src/store/clients.js +++ b/src/store/clients.js @@ -1,6 +1,12 @@ import ClientService from '@/services/client.service'; import Client from '@/store/models/client'; +function getClientById(clientId) { + return Client.query() + .with(['bank_account', 'fields']) + .find(clientId); +} + export default { namespaced: true, state: { @@ -32,13 +38,15 @@ export default { commit('clientId', client.id); Client.insert({ data: client }); }, - async createNewClient(store, client) { + async createNewClient({ dispatch }, client) { if (!client.hasOwnProperty('id')) { client = new Client(client); } + await dispatch('clientFields/addAllFields', client.id, { root: true }); + const res = await ClientService.createClient(client); await Client.insert({ data: res }); - return Client.find(res.id); + return getClientById(res.id); }, clientProps({ state }, props) { return Client.update({ @@ -53,9 +61,7 @@ export default { return ClientService.updateClient(getters.client); }, async updateClientById(store, payload) { - const client = Client.query() - .with('fields') - .find(payload.clientId); + const client = getClientById(payload.clientId); client.$update(payload.props); return ClientService.updateClient(client); }, @@ -72,9 +78,7 @@ export default { }, getters: { client(state) { - return Client.query() - .with(['bank_account', 'fields']) - .find(state.clientId); + return getClientById(state.clientId); }, all() { return Client.query()