further conversions to general makeFetch and toasts

This commit is contained in:
Julie Lenaerts 2021-12-01 10:43:18 +01:00
parent fb9df1dba0
commit e94bbc1271
10 changed files with 229 additions and 283 deletions

View File

@ -10,7 +10,7 @@
<script>
import AddAddress from './components/AddAddress.vue';
import { postAddressToHousehold, postAddressToPerson } from "ChillPersonAssets/vuejs/_api/AddAddress";
import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods.js';
export default {
name: "App",
@ -31,25 +31,17 @@ export default {
: this.context.target.name + '_' + this.context.target.id ;
}
},
mounted() {
//console.log('AddAddress: data context', this.context);
//console.log('AddAddress: data options', this.options);
},
methods: {
displayErrors() {
return this.$refs.addAddress.errorMsg;
},
submitAddress(payload) {
console.log('@@@ click on Submit Address Button', payload);
// Existing address
if (this.context.edit) {
// address is already linked, just finish !
this.$refs.addAddress.afterLastPaneAction({});
this.$emit('addressEdited', payload);
// New created address
// New created address
} else {
this.postAddressTo(payload);
}
@ -60,51 +52,39 @@ export default {
*/
postAddressTo(payload) {
this.$emit('addressCreated', payload);
let url = '';
console.log('postAddress', payload.addressId, 'To', payload.target, payload.targetId);
switch (payload.target) {
case 'household':
postAddressToHousehold(payload.targetId, payload.addressId)
.then(address => new Promise((resolve, reject) => {
console.log('..household address', address);
this.$refs.addAddress.flag.loading = false;
this.$refs.addAddress.flag.success = true;
// finish
this.$refs.addAddress.afterLastPaneAction({ addressId: address.address_id });
resolve();
}))
.catch((error) => {
this.$refs.addAddress.errorMsg.push(error);
this.$refs.addAddress.flag.loading = false;
})
;
url = `/api/1.0/person/household/${payload.targetId}/address.json`
break;
case 'person':
postAddressToPerson(payload.targetId, payload.addressId)
.then(address => new Promise((resolve, reject) => {
console.log('..person address', address);
this.$refs.addAddress.flag.loading = false;
this.$refs.addAddress.flag.success = true;
// finish
this.$refs.addAddress.afterLastPaneAction({ addressId: address.address_id });
resolve();
}))
.catch((error) => {
this.$refs.addAddress.errorMsg.push(error);
this.$refs.addAddress.flag.loading = false;
})
;
url = `/api/1.0/person/person/${payload.targetId}/address.json`
break;
case 'thirdparty':
console.log('TODO write postAddressToThirdparty');
// TODO write postAddressToThirdparty;
break;
default:
this.$refs.addAddress.errorMsg.push('That entity is not managed by address !');
this.$refs.addAddress.errorMsg.push('This entity is not managed by address !');
}
const body = {
'id': payload.addressId
};
makeFetch('POST', url, body)
.then((response) => {
this.$refs.addAddress.flag.loading = false;
this.$refs.addAddress.flag.success = true;
this.$refs.addAddress.afterLastPaneAction({ addressId: response.address_id });
})
.catch(({name, violations}) => {
if (name === 'ValidationException' || name === 'AccessException') {
violations.forEach((violation) => this.$toast.open({message: violation}));
} else {
this.$toast.open({message: 'An error occurred'})
}
this.$refs.addAddress.flag.loading = false;
});
}
}
}

View File

@ -36,12 +36,12 @@ const fetchCities = (country) => {
*/
const fetchReferenceAddresses = (postalCode) => {
//console.log('<<< fetching references addresses for', postalCode);
const url = `/api/1.0/main/address-reference.json?item_per_page=1000&postal_code=${postalCode.id}`;
return fetch(url)
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
const url = `/api/1.0/main/address-reference.json?item_per_page=1000&postal_code=${postalCode.id}`;
return fetch(url)
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
/**
@ -87,18 +87,18 @@ const postAddress = (address) => {
* @returns {Promise<Response>}
*/
const duplicateAddress = (address) => {
const url = `/api/1.0/main/address/${address.address_id}/duplicate.json`;
return fetch(url, {
'method': 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}).then(response => {
if (response.ok) {
return response.json();
}
throw Error('Error with request resource response');
});
const url = `/api/1.0/main/address/${address.address_id}/duplicate.json`;
return fetch(url, {
'method': 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
}).then(response => {
if (response.ok) {
return response.json();
}
throw Error('Error with request resource response');
});
};
@ -114,7 +114,7 @@ const patchAddress = (id, body) => {
return fetch(url, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json;charset=utf-8'
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(body)
})

View File

@ -220,16 +220,15 @@
<script>
import Modal from 'ChillMainAssets/vuejs/_components/Modal';
import {
duplicateAddress,
fetchCountries,
fetchCities,
fetchReferenceAddresses,
getAddress,
patchAddress,
postAddress,
postPostalCode,
duplicateAddress,
fetchCountries,
fetchCities,
fetchReferenceAddresses,
getAddress,
patchAddress,
postAddress,
postPostalCode,
} from '../api';
import { postAddressToPerson, postAddressToHousehold } from "ChillPersonAssets/vuejs/_api/AddAddress.js";
import ShowPane from './ShowPane.vue';
import SuggestPane from './SuggestPane.vue';
import EditPane from './EditPane.vue';
@ -246,7 +245,7 @@ export default {
DatePane
},
emits: {
pickAddress: null
pickAddress: null
},
data() {
return {
@ -355,14 +354,7 @@ export default {
}
},
mounted() {
//console.log('validFrom', this.validFrom);
//console.log('validTo', this.validTo);
//console.log('useDatePane', this.useDatePane);
// console.log('Mounted now !');
if (this.context.edit) {
// console.log('getInitialAddress', this.context.addressId);
this.getInitialAddress(this.context.addressId);
}
this.openShowPane();
@ -598,9 +590,9 @@ export default {
// add the address reference, if any
if (this.entity.selected.address.addressReference !== undefined) {
newAddress = Object.assign(newAddress, {
'addressReference': this.entity.selected.address.addressReference
});
newAddress = Object.assign(newAddress, {
'addressReference': this.entity.selected.address.addressReference
});
}
if (this.validFrom) {
@ -678,8 +670,8 @@ export default {
this.flag.loading = false;
this.flag.success = true;
resolve({
address,
targetOrigin: this.context.target,
address,
targetOrigin: this.context.target,
// for "legacy" use:
target: this.context.target.name,
targetId: this.context.target.id,
@ -729,8 +721,8 @@ export default {
this.flag.loading = false;
this.flag.success = true;
return resolve({
address,
targetOrigin: this.context.target,
address,
targetOrigin: this.context.target,
// for "legacy" use:
target: this.context.target.name,
targetId: this.context.target.id,
@ -744,7 +736,7 @@ export default {
});
},
/**
/**
*
* Called when the event pick-address is emitted, which is, by the way,
* called when an address suggestion is picked.
@ -754,19 +746,19 @@ export default {
pickAddress(address) {
// console.log('pickAddress', address);
duplicateAddress(address).then(newAddress => {
this.entity.address = newAddress;
this.flag.loading = false;
this.flag.success = true;
let payload = {
address: newAddress,
targetOrigin: this.context.target,
// for "legacy" use:
target: this.context.target.name,
targetId: this.context.target.id,
addressId: this.entity.address.address_id
};
this.addressChangedCallback(payload);
this.closeSuggestPane();
this.entity.address = newAddress;
this.flag.loading = false;
this.flag.success = true;
let payload = {
address: newAddress,
targetOrigin: this.context.target,
// for "legacy" use:
target: this.context.target.name,
targetId: this.context.target.id,
addressId: this.entity.address.address_id
};
this.addressChangedCallback(payload);
this.closeSuggestPane();
});
}
}

View File

@ -110,15 +110,15 @@ export default {
)
// filter persons appearing twice in requestor and resources
.filter(
(e, index, suggested) => {
for (let i = 0; i < suggested.length; i = i+1) {
if (i < index && e.id === suggested[i].id) {
return false
}
(e, index, suggested) => {
for (let i = 0; i < suggested.length; i = i+1) {
if (i < index && e.id === suggested[i].id) {
return false
}
}
return true;
}
return true;
}
)
}),
...mapGetters([

View File

@ -5,8 +5,6 @@ import { getAccompanyingCourse,
getReferrersSuggested,
getUsers,
} from '../api';
import { patchPerson } from "ChillPersonAssets/vuejs/_api/OnTheFly";
import { patchThirdparty } from "ChillThirdPartyAssets/vuejs/_api/OnTheFly";
import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods';
@ -17,7 +15,7 @@ let scopesPromise = fetchScopes();
let accompanyingCoursePromise = getAccompanyingCourse(id);
let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
.then(([scopes, accompanyingCourse]) => new Promise((resolve, reject) => {
.then(([scopes, accompanyingCourse]) => new Promise((resolve, reject) => {
const store = createStore({
strict: debug,
@ -355,15 +353,14 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
},
/**
* On The Fly
* ? should be into the dedicated component, no ? JF
* I think it's better to leave it here, because this action is dispatched in 3 different components,
* so lots of code repitition if we would put this in the components themselves.
*/
patchOnTheFly({ commit }, payload) {
// TODO should be into the dedicated component, no ? JF
// console.log('## action: patch OnTheFly', payload);
let body = { type: payload.type };
if (payload.type === 'person') {
const id = payload.data.id;
const url = `/api/1.0/person/person/${id}.json`;
body.firstName = payload.data.firstName;
body.lastName = payload.data.lastName;
if (payload.data.birthdate !== null) { body.birthdate = payload.data.birthdate; }
@ -371,50 +368,27 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
body.mobilenumber = payload.data.mobilenumber;
body.gender = payload.data.gender;
makeFetch('PATCH', url, body)
.then((response) => {
commit('updatePerson', {target: payload.target, person: response});
})
.catch((error) => {
commit('catchError', error);
throw error;
})
// console.log('id', payload.data.id, 'and body', body);
// patchPerson(payload.data.id, body)
// .then(person => new Promise((resolve, reject) => {
// // console.log('patch person', person);
// commit('updatePerson', { target: payload.target, person: person });
// resolve();
// }));
}
else if (payload.type === 'thirdparty') {
const id = payload.data.id;
const url = `/api/1.0/person/person/${id}.json`;
const mutation = 'updatePerson'
} else if (payload.type === 'thirdparty') {
body.name = payload.data.text;
body.email = payload.data.email;
body.telephone = payload.data.phonenumber;
body.address = { id: payload.data.address.address_id };
// console.log('id', payload.data.id, 'and body', body);
// patchThirdparty(payload.data.id, body)
// .then(thirdparty => new Promise((resolve, reject) => {
// console.log('patch thirdparty', thirdparty);
// commit('updateThirdparty', { target: payload.target, thirdparty: thirdparty });
// resolve();
// }));
const id = payload.data.id;
const url = `/api/1.0/thirdparty/thirdparty/${id}.json`;
makeFetch('PATCH', url, body)
.then((response) => {
commit('updateThirdparty', {target: payload.target, thirdparty: response});
})
.catch((error) => {
commit('catchError', error);
throw error;
})
const mutation = 'updateThirdparty'
}
makeFetch('PATCH', url, body)
.then((response) => {
commit(mutation, {target: payload.target, thirdparty: response});
})
.catch((error) => {
commit('catchError', error);
throw error;
})
},
/**
* Update accompanying course intensity/emergency/confidentiality
@ -509,23 +483,22 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
let checkedScopesIds = scopes.map(scope => scope.id);
let removedScopesIds = currentServerScopesIds.filter(id => !checkedScopesIds.includes(id));
let addedScopesIds = checkedScopesIds.filter(id => !currentServerScopesIds.includes(id));
let lengthAfterOperation = currentServerScopesIds.length + addedScopesIds.length
- removedScopesIds.length;
let lengthAfterOperation = currentServerScopesIds.length + addedScopesIds.length - removedScopesIds.length;
return dispatch('updateScopes', {
addedScopesIds, removedScopesIds
})
.catch(error => {
.catch(error => {
throw error;
})
.then(() => {
.then(() => {
// warning: when the operation of dispatch are too slow, the user may check / uncheck before
// the end of the synchronisation with the server (done by dispatch operation). Then, it leads to
// check/uncheck in the UI. I do not know of to avoid it.
commit('setScopes', scopes);
return Promise.resolve();
})
.then(() => {
.then(() => {
return dispatch('fetchReferrersSuggested');
});
/*
@ -651,10 +624,10 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
let users = await getReferrersSuggested(state.accompanyingCourse);
commit('setReferrersSuggested', users);
if (
null === state.accompanyingCourse.user
&& !state.accompanyingCourse.confidential
&& !state.accompanyingCourse.step === 'DRAFT'
&& users.length === 1
null === state.accompanyingCourse.user
&& !state.accompanyingCourse.confidential
&& !state.accompanyingCourse.step === 'DRAFT'
&& users.length === 1
) {
// set the user if unique
commit('updateReferrer', users[0]);
@ -673,11 +646,11 @@ let initPromise = Promise.all([scopesPromise, accompanyingCoursePromise])
"object": {
"type": "accompanying_period",
"id": id
},
"class": "Chill\\PersonBundle\\Entity\\AccompanyingPeriod",
"roles": [
"CHILL_PERSON_ACCOMPANYING_PERIOD_TOGGLE_CONFIDENTIAL"
]
},
"class": "Chill\\PersonBundle\\Entity\\AccompanyingPeriod",
"roles": [
"CHILL_PERSON_ACCOMPANYING_PERIOD_TOGGLE_CONFIDENTIAL"
]
}
return makeFetch('POST', url, body)

View File

@ -1,51 +1,51 @@
/*
* Endpoint chill_api_single_person_address
* method POST, post Person instance
*
* @id integer - id of Person
* @body Object - dictionary with changes to post
*/
const postAddressToPerson = (personId, addressId) => {
//console.log(personId);
//console.log(addressId);
const body = {
'id': addressId
};
const url = `/api/1.0/person/person/${personId}/address.json`
return fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json;charset=utf-8'},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
// /*
// * Endpoint chill_api_single_person_address
// * method POST, post Person instance
// *
// * @id integer - id of Person
// * @body Object - dictionary with changes to post
// */
// const postAddressToPerson = (personId, addressId) => {
// //console.log(personId);
// //console.log(addressId);
// const body = {
// 'id': addressId
// };
// const url = `/api/1.0/person/person/${personId}/address.json`
// return fetch(url, {
// method: 'POST',
// headers: {'Content-Type': 'application/json;charset=utf-8'},
// body: JSON.stringify(body)
// })
// .then(response => {
// if (response.ok) { return response.json(); }
// throw Error('Error with request resource response');
// });
// };
/*
* Endpoint household
* method POST, post Household instance
*
* @id integer - id of household
* @body Object - dictionary with changes to post
*/
const postAddressToHousehold = (householdId, addressId) => {
const body = {
'id': addressId
};
const url = `/api/1.0/person/household/${householdId}/address.json`
return fetch(url, {
method: 'POST',
headers: {'Content-Type': 'application/json;charset=utf-8'},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
// /*
// * Endpoint household
// * method POST, post Household instance
// *
// * @id integer - id of household
// * @body Object - dictionary with changes to post
// */
// const postAddressToHousehold = (householdId, addressId) => {
// const body = {
// 'id': addressId
// };
// const url = `/api/1.0/person/household/${householdId}/address.json`
// return fetch(url, {
// method: 'POST',
// headers: {'Content-Type': 'application/json;charset=utf-8'},
// body: JSON.stringify(body)
// })
// .then(response => {
// if (response.ok) { return response.json(); }
// throw Error('Error with request resource response');
// });
// };
export { postAddressToPerson, postAddressToHousehold };
// export { postAddressToPerson, postAddressToHousehold };

View File

@ -3,16 +3,16 @@
*/
const parametersToString = ({ query, options }) => {
let types ='';
options.type.forEach(function(type) {
options.type.forEach(function(type) {
types += '&type[]=' + type;
});
});
return 'q=' + query + types;
};
/*
/*
* Endpoint chill_person_search
* method GET, get a list of persons
*
*
* @query string - the query to search for
*/
const searchPersons = ({ query, options }) => {
@ -25,10 +25,10 @@ const searchPersons = ({ query, options }) => {
});
};
/*
/*
* Endpoint v.2 chill_main_search_global
* method GET, get a list of persons and thirdparty
*
*
* NOTE: this is a temporary WIP endpoint, return inconsistent random results
* @query string - the query to search for
*/

View File

@ -1,53 +1,53 @@
/*
* GET a person by id
*/
const getPerson = (id) => {
const url = `/api/1.0/person/person/${id}.json`;
return fetch(url)
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
// const getPerson = (id) => {
// const url = `/api/1.0/person/person/${id}.json`;
// return fetch(url)
// .then(response => {
// if (response.ok) { return response.json(); }
// throw Error('Error with request resource response');
// });
// };
/*
* POST a new person
*/
const postPerson = (body) => {
const url = `/api/1.0/person/person.json`;
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
// const postPerson = (body) => {
// const url = `/api/1.0/person/person.json`;
// return fetch(url, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json;charset=utf-8'
// },
// body: JSON.stringify(body)
// })
// .then(response => {
// if (response.ok) { return response.json(); }
// throw Error('Error with request resource response');
// });
// };
/*
* PATCH an existing person
*/
const patchPerson = (id, body) => {
const url = `/api/1.0/person/person/${id}.json`;
return fetch(url, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) { return response.json(); }
throw Error('Error with request resource response');
});
};
// const patchPerson = (id, body) => {
// const url = `/api/1.0/person/person/${id}.json`;
// return fetch(url, {
// method: 'PATCH',
// headers: {
// 'Content-Type': 'application/json;charset=utf-8'
// },
// body: JSON.stringify(body)
// })
// .then(response => {
// if (response.ok) { return response.json(); }
// throw Error('Error with request resource response');
// });
// };
export {
getPerson,
postPerson,
patchPerson
// getPerson,
// postPerson,
// patchPerson
};

View File

@ -257,28 +257,22 @@ export default {
saveFormOnTheFly({ type, data }) {
// console.log('saveFormOnTheFly from addPersons, type', type, ', data', data);
if (type === 'person') {
// console.log('type person with', data);
postPerson(data)
.then(person => new Promise((resolve, reject) => {
// console.log('onthefly create: post person', person);
this.newPriorSuggestion(person);
resolve();
}));
const url = `/api/1.0/person/person.json`;
}
else if (type === 'thirdparty') {
const url = `/api/1.0/thirdparty/thirdparty.json`;
makeFetch('POST', url, data)
.then((response) => {
this.newPriorSuggestion(response);
})
.catch(({name, violations}) => {
if (name === 'ValidationException' || name === 'AccessException') {
violations.forEach((violation) => this.$toast.open({message: violation}));
} else {
this.$toast.open({message: 'An error occurred'})
}
});
}
makeFetch('POST', url, data)
.then((response) => {
this.newPriorSuggestion(response);
})
.catch(({name, violations}) => {
if (name === 'ValidationException' || name === 'AccessException') {
violations.forEach((violation) => this.$toast.open({message: violation}));
} else {
this.$toast.open({message: 'An error occurred'})
}
});
}
},
}

View File

@ -76,6 +76,7 @@
<script>
import { getPerson } from '../../_api/OnTheFly';
import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods';
import PersonRenderBox from '../Entity/PersonRenderBox.vue';
export default {
@ -156,12 +157,18 @@ export default {
},
methods: {
loadData() {
getPerson(this.id)
.then(person => new Promise((resolve, reject) => {
this.person = person;
console.log('get person', this.person);
resolve();
}));
const url = `/api/1.0/person/person/${this.id}.json`;
makeFetch('GET', url)
.then((response) => {
this.person = response;
})
.catch(({name, violations}) => {
if (name === 'ValidationException' || name === 'AccessException') {
violations.forEach((violation) => this.$toast.open({message: violation}));
} else {
this.$toast.open({message: 'An error occurred'})
}
});
}
}
}