From f90f1c7ef85f661633b851ffe0dc48d2731fc522 Mon Sep 17 00:00:00 2001 From: Julie Lenaerts Date: Thu, 31 Oct 2024 17:27:45 +0100 Subject: [PATCH 01/22] Install eslint and eslint vue plugin + config file --- eslint.config.mjs | 11 +++++++++++ package.json | 4 +++- 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 eslint.config.mjs diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 000000000..025a969c2 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,11 @@ +import pluginVue from 'eslint-plugin-vue' + +export default [ + ...pluginVue.configs['flat/strongly-recommended'], + { + rules: { + // override/add rules settings here, such as: + // 'vue/no-unused-vars': 'error' + } + } +] diff --git a/package.json b/package.json index 8f741d3e9..23b82baa2 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,9 @@ "typescript": "^5.4.5", "vue-loader": "^17.0.0", "webpack": "^5.75.0", - "webpack-cli": "^5.0.1" + "webpack-cli": "^5.0.1", + "eslint": "^9.13.0", + "eslint-plugin-vue": "^9.30.0" }, "dependencies": { "@fullcalendar/core": "^6.1.4", From 27ecae448619988a7f192246566935517989a129 Mon Sep 17 00:00:00 2001 From: Julie Lenaerts Date: Thu, 31 Oct 2024 17:28:02 +0100 Subject: [PATCH 02/22] first eslint corrections --- .../Resources/public/vuejs/Activity/App.vue | 6 +- .../Activity/components/ConcernedGroups.vue | 75 +- .../ConcernedGroups/PersonBadge.vue | 18 +- .../ConcernedGroups/PersonsBloc.vue | 35 +- .../vuejs/Activity/components/Location.vue | 57 +- .../components/Location/NewLocation.vue | 195 +++-- .../Activity/components/SocialIssuesAcc.vue | 141 ++-- .../SocialIssuesAcc/CheckSocialAction.vue | 32 +- .../SocialIssuesAcc/CheckSocialIssue.vue | 32 +- .../Resources/public/vuejs/Calendar/App.vue | 265 ++++-- .../Calendar/Components/CalendarActive.vue | 51 +- .../CalendarUserSelector.vue | 67 +- .../public/vuejs/_components/PickTemplate.vue | 93 +- .../vuejs/_components/AddAsyncUpload.vue | 136 +-- .../_components/AddAsyncUploadDownloader.vue | 10 +- .../Resources/public/vuejs/Address/App.vue | 14 +- .../Address/components/ActionButtons.vue | 36 +- .../vuejs/Address/components/AddAddress.vue | 491 ++++++----- .../components/AddAddress/AddressMap.vue | 2 +- .../components/AddAddress/AddressMore.vue | 153 ++-- .../AddAddress/AddressSelection.vue | 102 ++- .../components/AddAddress/CitySelection.vue | 99 ++- .../AddAddress/CountrySelection.vue | 38 +- .../vuejs/Address/components/DatePane.vue | 117 ++- .../vuejs/Address/components/EditPane.vue | 205 +++-- .../vuejs/Address/components/ShowPane.vue | 165 ++-- .../vuejs/Address/components/SuggestPane.vue | 108 ++- .../public/vuejs/HomepageWidget/App.vue | 171 ++-- .../HomepageWidget/MyAccompanyingCourses.vue | 117 ++- .../public/vuejs/HomepageWidget/MyCustoms.vue | 149 ++-- .../vuejs/HomepageWidget/MyEvaluations.vue | 128 +-- .../vuejs/HomepageWidget/MyNotifications.vue | 78 +- .../public/vuejs/HomepageWidget/MyTasks.vue | 136 +-- .../vuejs/HomepageWidget/MyWorkflows.vue | 12 +- .../vuejs/HomepageWidget/MyWorkflowsTable.vue | 95 ++- .../public/vuejs/HomepageWidget/MyWorks.vue | 126 +-- .../vuejs/HomepageWidget/TabCounter.vue | 10 +- .../public/vuejs/HomepageWidget/TabTable.vue | 20 +- .../Resources/public/vuejs/OnTheFly/App.vue | 20 +- .../vuejs/OnTheFly/components/Create.vue | 90 +- .../vuejs/OnTheFly/components/OnTheFly.vue | 194 +++-- .../public/vuejs/PickEntity/PickEntity.vue | 54 +- .../vuejs/PickPostalCode/PickPostalCode.vue | 45 +- .../public/vuejs/_components/BadgeEntity.vue | 68 +- .../public/vuejs/_components/Confidential.vue | 19 +- .../_components/Entity/AddressRenderBox.vue | 148 ++-- .../Entity/GenderIconRenderBox.vue | 2 +- .../_components/Entity/UserRenderBoxBadge.vue | 16 +- .../EntityWorkflowVueSubscriber.vue | 56 +- .../EntityWorkflow/ListWorkflow.vue | 133 +-- .../EntityWorkflow/ListWorkflowModal.vue | 93 +- .../EntityWorkflow/PickWorkflow.vue | 40 +- .../public/vuejs/_components/Modal.vue | 67 +- .../Notification/NotificationReadToggle.vue | 117 +-- .../public/vuejs/_components/OpenWopiLink.vue | 124 +-- .../public/vuejs/AccompanyingCourse/App.vue | 38 +- .../components/AdminLocation.vue | 59 +- .../AccompanyingCourse/components/Banner.vue | 148 ++-- .../components/Banner/PersonsAssociated.vue | 36 +- .../components/Banner/ToggleFlags.vue | 48 +- .../components/ButtonLocation.vue | 57 +- .../AccompanyingCourse/components/Comment.vue | 91 +- .../AccompanyingCourse/components/Confirm.vue | 207 +++-- .../components/CourseLocation.vue | 141 ++-- .../components/OriginDemand.vue | 55 +- .../components/PersonsAssociated.vue | 153 ++-- .../PersonsAssociated/ParticipationItem.vue | 142 ++-- .../components/Referrer.vue | 122 +-- .../components/Requestor.vue | 339 +++++--- .../components/Resources.vue | 75 +- .../components/Resources/ResourceItem.vue | 201 ++--- .../components/Resources/WriteComment.vue | 71 +- .../AccompanyingCourse/components/Scopes.vue | 35 +- .../components/SocialIssue.vue | 46 +- .../components/StartDate.vue | 25 +- .../components/StickyNav.vue | 35 +- .../components/StickyNav/Item.vue | 32 +- .../AccompanyingCourse/components/Test.vue | 119 +-- .../AccompanyingCourseWorkCreate/App.vue | 156 ++-- .../vuejs/AccompanyingCourseWorkEdit/App.vue | 791 +++++++++++------- .../components/AddEvaluation.vue | 115 ++- .../components/AddResult.vue | 133 +-- .../components/FormEvaluation.vue | 380 +++++---- .../vuejs/ExportFormActionGoalResult/App.vue | 140 ++-- .../vuejs/HouseholdMembersEditor/App.vue | 58 +- .../components/Concerned.vue | 42 +- .../components/Confirmation.vue | 17 +- .../components/CurrentHousehold.vue | 22 +- .../components/Dates.vue | 35 +- .../components/Household.vue | 116 ++- .../components/HouseholdAddress.vue | 19 +- .../components/MemberDetails.vue | 47 +- .../components/PersonComment.vue | 12 +- .../components/Positioning.vue | 86 +- .../Resources/public/vuejs/VisGraph/App.vue | 275 +++--- .../AccompanyingPeriod/SetReferrer.vue | 15 +- .../public/vuejs/_components/AddPersons.vue | 183 ++-- .../AddPersons/PersonSuggestion.vue | 64 +- .../_components/AddPersons/TypeHousehold.vue | 21 +- .../_components/AddPersons/TypePerson.vue | 52 +- .../_components/AddPersons/TypeThirdParty.vue | 77 +- .../vuejs/_components/AddPersons/TypeUser.vue | 20 +- .../_components/Entity/HouseholdRenderBox.vue | 121 +-- .../_components/Entity/PersonRenderBox.vue | 291 ++++--- .../vuejs/_components/Entity/PersonText.vue | 32 +- .../vuejs/_components/OnTheFly/Person.vue | 393 +++++---- .../Entity/ThirdPartyRenderBox.vue | 86 +- .../_components/Entity/ThirdPartyText.vue | 11 +- .../vuejs/_components/OnTheFly/ThirdParty.vue | 384 +++++---- 109 files changed, 6903 insertions(+), 4637 deletions(-) diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/App.vue b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/App.vue index 4809a5fae..bcd8f2db1 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/App.vue +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/App.vue @@ -1,7 +1,7 @@ diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/api.js b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/api.js index a520f22c4..1d6075dee 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/api.js +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/api.js @@ -1,38 +1,39 @@ -import { getSocialIssues } from 'ChillPersonAssets/vuejs/AccompanyingCourse/api.js'; -import { fetchResults } from 'ChillMainAssets/lib/api/apiMethods'; +import { getSocialIssues } from "ChillPersonAssets/vuejs/AccompanyingCourse/api.js"; +import { fetchResults } from "ChillMainAssets/lib/api/apiMethods"; /* -* Load socialActions by socialIssue (id) -*/ + * Load socialActions by socialIssue (id) + */ const getSocialActionByIssue = (id) => { - const url = `/api/1.0/person/social/social-action/by-social-issue/${id}.json`; - return fetch(url) - .then(response => { - if (response.ok) { return response.json(); } - throw Error('Error with request resource response'); - }); + const url = `/api/1.0/person/social/social-action/by-social-issue/${id}.json`; + return fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } + throw Error("Error with request resource response"); + }); }; -const getLocations = () => fetchResults('/api/1.0/main/location.json'); +const getLocations = () => fetchResults("/api/1.0/main/location.json"); -const getLocationTypes = () => fetchResults('/api/1.0/main/location-type.json'); - -const getUserCurrentLocation = - () => fetch('/api/1.0/main/user-current-location.json') - .then(response => { - if (response.ok) { return response.json(); } - throw Error('Error with request resource response'); - }); +const getLocationTypes = () => fetchResults("/api/1.0/main/location-type.json"); +const getUserCurrentLocation = () => + fetch("/api/1.0/main/user-current-location.json").then((response) => { + if (response.ok) { + return response.json(); + } + throw Error("Error with request resource response"); + }); /* -* Load Location Type by defaultFor -* @param {string} entity - can be "person" or "thirdparty" + * Load Location Type by defaultFor + * @param {string} entity - can be "person" or "thirdparty" */ const getLocationTypeByDefaultFor = (entity) => { - return getLocationTypes().then(results => - results.filter(t => t.defaultFor === entity)[0] - ); + return getLocationTypes().then( + (results) => results.filter((t) => t.defaultFor === entity)[0], + ); }; /** @@ -43,26 +44,27 @@ const getLocationTypeByDefaultFor = (entity) => { * @returns {Promise} */ const postLocation = (body) => { - const url = `/api/1.0/main/location.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 url = `/api/1.0/main/location.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 { - getSocialIssues, - getSocialActionByIssue, - getLocations, - getLocationTypes, - getLocationTypeByDefaultFor, - postLocation, - getUserCurrentLocation + getSocialIssues, + getSocialActionByIssue, + getLocations, + getLocationTypes, + getLocationTypeByDefaultFor, + postLocation, + getUserCurrentLocation, }; diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups.vue b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups.vue index 83f6be91c..8437a1524 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups.vue +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups.vue @@ -1,230 +1,242 @@ - + diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonBadge.vue b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonBadge.vue index ed2086648..7e839168e 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonBadge.vue +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonBadge.vue @@ -1,38 +1,30 @@ - + diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonsBloc.vue b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonsBloc.vue index 7c96cf718..c09e122a9 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonsBloc.vue +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/ConcernedGroups/PersonsBloc.vue @@ -1,44 +1,39 @@ - + diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/Location.vue b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/Location.vue index 71a4621d7..efa1ca9e5 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/Location.vue +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/Location.vue @@ -1,32 +1,32 @@ diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc.vue b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc.vue index b276672ab..a055fa725 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc.vue +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc.vue @@ -1,228 +1,243 @@ diff --git a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc/CheckSocialAction.vue b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc/CheckSocialAction.vue index e6f47134c..0d5a6bbf4 100644 --- a/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc/CheckSocialAction.vue +++ b/src/Bundle/ChillActivityBundle/Resources/public/vuejs/Activity/components/SocialIssuesAcc/CheckSocialAction.vue @@ -1,48 +1,43 @@ diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/Components/CalendarActive.vue b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/Components/CalendarActive.vue index 26311101c..a51e7dd7c 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/Components/CalendarActive.vue +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/Components/CalendarActive.vue @@ -1,113 +1,119 @@ diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/api.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/api.ts index 17ef256ad..135b3ef1a 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/api.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/api.ts @@ -1,10 +1,10 @@ -import {fetchResults} from '../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods'; -import {datetimeToISO} from '../../../../../ChillMainBundle/Resources/public/chill/js/date'; -import {User} from '../../../../../ChillMainBundle/Resources/public/types'; -import {CalendarLight, CalendarRange, CalendarRemote} from '../../types'; +import { fetchResults } from "../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods"; +import { datetimeToISO } from "../../../../../ChillMainBundle/Resources/public/chill/js/date"; +import { User } from "../../../../../ChillMainBundle/Resources/public/types"; +import { CalendarLight, CalendarRange, CalendarRemote } from "../../types"; // re-export whoami -export {whoami} from "../../../../../ChillMainBundle/Resources/public/lib/api/user"; +export { whoami } from "../../../../../ChillMainBundle/Resources/public/lib/api/user"; /** * @@ -13,26 +13,38 @@ export {whoami} from "../../../../../ChillMainBundle/Resources/public/lib/api/us * @param Date end * @return Promise */ -export const fetchCalendarRangeForUser = (user: User, start: Date, end: Date): Promise => { - const uri = `/api/1.0/calendar/calendar-range-available/${user.id}.json`; - const dateFrom = datetimeToISO(start); - const dateTo = datetimeToISO(end); +export const fetchCalendarRangeForUser = ( + user: User, + start: Date, + end: Date, +): Promise => { + const uri = `/api/1.0/calendar/calendar-range-available/${user.id}.json`; + const dateFrom = datetimeToISO(start); + const dateTo = datetimeToISO(end); - return fetchResults(uri, {dateFrom, dateTo}); -} + return fetchResults(uri, { dateFrom, dateTo }); +}; -export const fetchCalendarRemoteForUser = (user: User, start: Date, end: Date): Promise => { - const uri = `/api/1.0/calendar/proxy/calendar/by-user/${user.id}/events`; - const dateFrom = datetimeToISO(start); - const dateTo = datetimeToISO(end); +export const fetchCalendarRemoteForUser = ( + user: User, + start: Date, + end: Date, +): Promise => { + const uri = `/api/1.0/calendar/proxy/calendar/by-user/${user.id}/events`; + const dateFrom = datetimeToISO(start); + const dateTo = datetimeToISO(end); - return fetchResults(uri, {dateFrom, dateTo}); -} + return fetchResults(uri, { dateFrom, dateTo }); +}; -export const fetchCalendarLocalForUser = (user: User, start: Date, end: Date): Promise => { - const uri = `/api/1.0/calendar/calendar/by-user/${user.id}.json`; - const dateFrom = datetimeToISO(start); - const dateTo = datetimeToISO(end); +export const fetchCalendarLocalForUser = ( + user: User, + start: Date, + end: Date, +): Promise => { + const uri = `/api/1.0/calendar/calendar/by-user/${user.id}.json`; + const dateFrom = datetimeToISO(start); + const dateTo = datetimeToISO(end); - return fetchResults(uri, {dateFrom, dateTo}); -} + return fetchResults(uri, { dateFrom, dateTo }); +}; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/const.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/const.ts index 05a0d5627..7d7cfaf74 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/const.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/const.ts @@ -1,19 +1,17 @@ - -const COLORS = [ /* from https://colorbrewer2.org/#type=qualitative&scheme=Set3&n=12 */ - '#8dd3c7', - '#ffffb3', - '#bebada', - '#fb8072', - '#80b1d3', - '#fdb462', - '#b3de69', - '#fccde5', - '#d9d9d9', - '#bc80bd', - '#ccebc5', - '#ffed6f' +const COLORS = [ + /* from https://colorbrewer2.org/#type=qualitative&scheme=Set3&n=12 */ + "#8dd3c7", + "#ffffb3", + "#bebada", + "#fb8072", + "#80b1d3", + "#fdb462", + "#b3de69", + "#fccde5", + "#d9d9d9", + "#bc80bd", + "#ccebc5", + "#ffed6f", ]; -export { - COLORS, -}; +export { COLORS }; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/i18n.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/i18n.js index c47218c4b..9e56d061b 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/i18n.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/i18n.js @@ -1,6 +1,6 @@ -import {personMessages} from 'ChillPersonAssets/vuejs/_js/i18n' -import {calendarUserSelectorMessages} from '../_components/CalendarUserSelector/js/i18n'; -import {activityMessages} from 'ChillActivityAssets/vuejs/Activity/i18n'; +import { personMessages } from "ChillPersonAssets/vuejs/_js/i18n"; +import { calendarUserSelectorMessages } from "../_components/CalendarUserSelector/js/i18n"; +import { activityMessages } from "ChillActivityAssets/vuejs/Activity/i18n"; const appMessages = { fr: { @@ -13,20 +13,22 @@ const appMessages = { bloc_thirdparty: "Tiers professionnels", bloc_users: "T(M)S", }, - this_calendar_range_will_change_main_user: "Cette plage de disponibilité n'est pas celle de l'utilisateur principal. Si vous continuez, l'utilisateur principal sera adapté. Êtes-vous sûr·e ?", - will_change_main_user_for_me: "Vous ne pouvez pas écrire dans le calendrier d'un autre utilisateur. Voulez-vous être l'utilisateur principal de ce rendez-vous ?", - main_user_is_mandatory: "L'utilisateur principal est requis. Vous pouvez le modifier, mais pas le supprimer", - change_main_user_will_reset_event_data: "Modifier l'utilisateur principal nécessite de choisir une autre plage de disponibilité ou un autre horaire. Ces informations seront perdues. Êtes-vous sûr·e de vouloir continuer ?", - list_three_days: 'Liste 3 jours', - current_selected: 'Rendez-vous fixé', + this_calendar_range_will_change_main_user: + "Cette plage de disponibilité n'est pas celle de l'utilisateur principal. Si vous continuez, l'utilisateur principal sera adapté. Êtes-vous sûr·e ?", + will_change_main_user_for_me: + "Vous ne pouvez pas écrire dans le calendrier d'un autre utilisateur. Voulez-vous être l'utilisateur principal de ce rendez-vous ?", + main_user_is_mandatory: + "L'utilisateur principal est requis. Vous pouvez le modifier, mais pas le supprimer", + change_main_user_will_reset_event_data: + "Modifier l'utilisateur principal nécessite de choisir une autre plage de disponibilité ou un autre horaire. Ces informations seront perdues. Êtes-vous sûr·e de vouloir continuer ?", + list_three_days: "Liste 3 jours", + current_selected: "Rendez-vous fixé", main_user: "Utilisateur principal", - } -} + }, +}; Object.assign(appMessages.fr, personMessages.fr); Object.assign(appMessages.fr, calendarUserSelectorMessages.fr); Object.assign(appMessages.fr, activityMessages.fr); -export { - appMessages -}; +export { appMessages }; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/index.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/index.js index d4c07f4a7..62c908f93 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/index.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/index.js @@ -1,16 +1,16 @@ -import { createApp } from 'vue'; -import { _createI18n } from 'ChillMainAssets/vuejs/_js/i18n' -import { appMessages } from './i18n' -import store from './store' +import { createApp } from "vue"; +import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n"; +import { appMessages } from "./i18n"; +import store from "./store"; -import App from './App.vue'; +import App from "./App.vue"; const i18n = _createI18n(appMessages); const app = createApp({ - template: ``, + template: ``, }) -.use(store) -.use(i18n) -.component('app', App) -.mount('#calendar'); + .use(store) + .use(i18n) + .component("app", App) + .mount("#calendar"); diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/actions.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/actions.js index 0e4d91afc..65f0c8050 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/actions.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/actions.js @@ -1,14 +1,11 @@ -import { - addIdToValue, - removeIdFromValue, -} from './utils'; +import { addIdToValue, removeIdFromValue } from "./utils"; import { fetchCalendarRangeForUser, fetchCalendarRemoteForUser, fetchCalendarLocalForUser, -} from './../api'; -import {datetimeToISO} from 'ChillMainAssets/chill/js/date'; -import {postLocation} from 'ChillActivityAssets/vuejs/Activity/api'; +} from "./../api"; +import { datetimeToISO } from "ChillMainAssets/chill/js/date"; +import { postLocation } from "ChillActivityAssets/vuejs/Activity/api"; /** * This will store a unique key for each value, and prevent to launch the same @@ -24,12 +21,12 @@ import {postLocation} from 'ChillActivityAssets/vuejs/Activity/api'; const fetchings = new Set(); export default { - setCurrentDatesView({commit, dispatch}, {start, end}) { - commit('setCurrentDatesView', {start, end}); + setCurrentDatesView({ commit, dispatch }, { start, end }) { + commit("setCurrentDatesView", { start, end }); - return dispatch('fetchCalendarEvents'); + return dispatch("fetchCalendarEvents"); }, - fetchCalendarEvents({state, getters, dispatch}) { + fetchCalendarEvents({ state, getters, dispatch }) { if (state.currentView.start === null && state.currentView.end === null) { return Promise.resolve(); } @@ -39,101 +36,124 @@ export default { let unique = `${uid}, ${state.currentView.start.toISOString()}, ${state.currentView.end.toISOString()}`; if (fetchings.has(unique)) { - console.log('prevent from fetching for a user', unique); + console.log("prevent from fetching for a user", unique); continue; } fetchings.add(unique); promises.push( - dispatch( - 'fetchCalendarRangeForUser', - {user: state.usersData.get(uid).user, start: state.currentView.start, end: state.currentView.end} - ) + dispatch("fetchCalendarRangeForUser", { + user: state.usersData.get(uid).user, + start: state.currentView.start, + end: state.currentView.end, + }), ); promises.push( - dispatch( - 'fetchCalendarRemotesForUser', - {user: state.usersData.get(uid).user, start: state.currentView.start, end: state.currentView.end} - ) + dispatch("fetchCalendarRemotesForUser", { + user: state.usersData.get(uid).user, + start: state.currentView.start, + end: state.currentView.end, + }), ); promises.push( - dispatch( - 'fetchCalendarLocalsForUser', - {user: state.usersData.get(uid).user, start: state.currentView.start, end: state.currentView.end} - ) + dispatch("fetchCalendarLocalsForUser", { + user: state.usersData.get(uid).user, + start: state.currentView.start, + end: state.currentView.end, + }), ); } return Promise.all(promises); }, - fetchCalendarRangeForUser({commit, getters}, {user, start, end}) { - if (!getters.isCalendarRangeLoadedForUser({user, start, end})) { + fetchCalendarRangeForUser({ commit, getters }, { user, start, end }) { + if (!getters.isCalendarRangeLoadedForUser({ user, start, end })) { return fetchCalendarRangeForUser(user, start, end).then((ranges) => { - commit('addCalendarRangesForUser', {user, ranges, start, end}); + commit("addCalendarRangesForUser", { user, ranges, start, end }); return Promise.resolve(); }); } }, - fetchCalendarRemotesForUser({commit, getters}, {user, start, end}) { - if (!getters.isCalendarRemoteLoadedForUser({user, start, end})) { + fetchCalendarRemotesForUser({ commit, getters }, { user, start, end }) { + if (!getters.isCalendarRemoteLoadedForUser({ user, start, end })) { return fetchCalendarRemoteForUser(user, start, end).then((remotes) => { - commit('addCalendarRemotesForUser', {user, remotes, start, end}); + commit("addCalendarRemotesForUser", { user, remotes, start, end }); return Promise.resolve(); }); } }, - fetchCalendarLocalsForUser({commit, getters}, {user, start, end}) { - if (!getters.isCalendarRemoteLoadedForUser({user, start, end})) { + fetchCalendarLocalsForUser({ commit, getters }, { user, start, end }) { + if (!getters.isCalendarRemoteLoadedForUser({ user, start, end })) { return fetchCalendarLocalForUser(user, start, end).then((locals) => { - commit('addCalendarLocalsForUser', {user, locals, start, end}); + commit("addCalendarLocalsForUser", { user, locals, start, end }); return Promise.resolve(); }); } }, - addPersonsInvolved({commit, dispatch}, payload) { - console.log('### action addPersonsInvolved', payload.result.type); - console.log('### action addPersonsInvolved payload result', payload.result); + addPersonsInvolved({ commit, dispatch }, payload) { + console.log("### action addPersonsInvolved", payload.result.type); + console.log("### action addPersonsInvolved payload result", payload.result); switch (payload.result.type) { - case 'person': - let aPersons = document.getElementById("chill_activitybundle_activity_persons"); + case "person": + let aPersons = document.getElementById( + "chill_activitybundle_activity_persons", + ); aPersons.value = addIdToValue(aPersons.value, payload.result.id); break; - case 'thirdparty': - let aThirdParties = document.getElementById("chill_activitybundle_activity_professionals"); - aThirdParties.value = addIdToValue(aThirdParties.value, payload.result.id); + case "thirdparty": + let aThirdParties = document.getElementById( + "chill_activitybundle_activity_professionals", + ); + aThirdParties.value = addIdToValue( + aThirdParties.value, + payload.result.id, + ); break; - case 'user': - let aUsers = document.getElementById("chill_activitybundle_activity_users"); + case "user": + let aUsers = document.getElementById( + "chill_activitybundle_activity_users", + ); aUsers.value = addIdToValue(aUsers.value, payload.result.id); - commit('showUserOnCalendar', {user: payload.result, ranges: false, remotes: true}); - dispatch('fetchCalendarEvents'); + commit("showUserOnCalendar", { + user: payload.result, + ranges: false, + remotes: true, + }); + dispatch("fetchCalendarEvents"); break; } - ; - commit('addPersonsInvolved', payload); + commit("addPersonsInvolved", payload); }, - removePersonInvolved({commit}, payload) { + removePersonInvolved({ commit }, payload) { //console.log('### action removePersonInvolved', payload); switch (payload.type) { - case 'person': - let aPersons = document.getElementById("chill_activitybundle_activity_persons"); + case "person": + let aPersons = document.getElementById( + "chill_activitybundle_activity_persons", + ); aPersons.value = removeIdFromValue(aPersons.value, payload.id); break; - case 'thirdparty': - let aThirdParties = document.getElementById("chill_activitybundle_activity_professionals"); - aThirdParties.value = removeIdFromValue(aThirdParties.value, payload.id); + case "thirdparty": + let aThirdParties = document.getElementById( + "chill_activitybundle_activity_professionals", + ); + aThirdParties.value = removeIdFromValue( + aThirdParties.value, + payload.id, + ); break; - case 'user': - let aUsers = document.getElementById("chill_activitybundle_activity_users"); + case "user": + let aUsers = document.getElementById( + "chill_activitybundle_activity_users", + ); aUsers.value = removeIdFromValue(aUsers.value, payload.id); break; } - ; - commit('removePersonInvolved', payload); + commit("removePersonInvolved", payload); }, // Calendar @@ -148,31 +168,49 @@ export default { * @param start * @param end */ - setEventTimes({commit, state, getters}, {start, end}) { - console.log('### action createEvent', {start, end}); - let startDateInput = document.getElementById("chill_activitybundle_activity_startDate"); - startDateInput.value = null !== start ? datetimeToISO(start) : ''; - let endDateInput = document.getElementById("chill_activitybundle_activity_endDate"); - endDateInput.value = null !== end ? datetimeToISO(end) : ''; - let calendarRangeInput = document.getElementById("chill_activitybundle_activity_calendarRange"); + setEventTimes({ commit, state, getters }, { start, end }) { + console.log("### action createEvent", { start, end }); + let startDateInput = document.getElementById( + "chill_activitybundle_activity_startDate", + ); + startDateInput.value = null !== start ? datetimeToISO(start) : ""; + let endDateInput = document.getElementById( + "chill_activitybundle_activity_endDate", + ); + endDateInput.value = null !== end ? datetimeToISO(end) : ""; + let calendarRangeInput = document.getElementById( + "chill_activitybundle_activity_calendarRange", + ); calendarRangeInput.value = ""; - if (getters.getMainUser === null || getters.getMainUser.id !== state.me.id) { - let mainUserInput = document.getElementById("chill_activitybundle_activity_mainUser"); + if ( + getters.getMainUser === null || + getters.getMainUser.id !== state.me.id + ) { + let mainUserInput = document.getElementById( + "chill_activitybundle_activity_mainUser", + ); mainUserInput.value = state.me.id; - commit('setMainUser', state.me); + commit("setMainUser", state.me); } - commit('setEventTimes', {start, end}); + commit("setEventTimes", { start, end }); }, - associateCalendarToRange({state, commit, dispatch, getters}, {range}) { - console.log('### action associateCAlendarToRange', range); - let startDateInput = document.getElementById("chill_activitybundle_activity_startDate"); + associateCalendarToRange({ state, commit, dispatch, getters }, { range }) { + console.log("### action associateCAlendarToRange", range); + let startDateInput = document.getElementById( + "chill_activitybundle_activity_startDate", + ); startDateInput.value = null !== range ? datetimeToISO(range.start) : ""; - let endDateInput = document.getElementById("chill_activitybundle_activity_endDate"); + let endDateInput = document.getElementById( + "chill_activitybundle_activity_endDate", + ); endDateInput.value = null !== range ? datetimeToISO(range.end) : ""; - let calendarRangeInput = document.getElementById("chill_activitybundle_activity_calendarRange"); - calendarRangeInput.value = null !== range ? Number(range.extendedProps.calendarRangeId) : ""; + let calendarRangeInput = document.getElementById( + "chill_activitybundle_activity_calendarRange", + ); + calendarRangeInput.value = + null !== range ? Number(range.extendedProps.calendarRangeId) : ""; if (null !== range) { let location = getters.getLocationById(range.extendedProps.locationId); @@ -181,63 +219,68 @@ export default { console.error("location not found!", range.extendedProps.locationId); } - dispatch('updateLocation', location); + dispatch("updateLocation", location); const userId = range.extendedProps.userId; - if (state.activity.mainUser !== null && state.activity.mainUser.id !== userId) { - dispatch('setMainUser', state.usersData.get(userId).user); + if ( + state.activity.mainUser !== null && + state.activity.mainUser.id !== userId + ) { + dispatch("setMainUser", state.usersData.get(userId).user); // TODO: remove persons involved with this user } } - commit('associateCalendarToRange', {range}); + commit("associateCalendarToRange", { range }); return Promise.resolve(); }, - setMainUser({commit, dispatch, state}, mainUser) { - console.log('setMainUser', mainUser); + setMainUser({ commit, dispatch, state }, mainUser) { + console.log("setMainUser", mainUser); - let mainUserInput = document.getElementById("chill_activitybundle_activity_mainUser"); + let mainUserInput = document.getElementById( + "chill_activitybundle_activity_mainUser", + ); mainUserInput.value = Number(mainUser.id); - return dispatch('associateCalendarToRange', { range: null }).then(() => { - commit('setMainUser', mainUser); + return dispatch("associateCalendarToRange", { range: null }).then(() => { + commit("setMainUser", mainUser); - return dispatch('fetchCalendarEvents'); + return dispatch("fetchCalendarEvents"); }); }, // Location - updateLocation({commit}, value) { - console.log('### action: updateLocation', value); - let hiddenLocation = document.getElementById("chill_activitybundle_activity_location"); + updateLocation({ commit }, value) { + console.log("### action: updateLocation", value); + let hiddenLocation = document.getElementById( + "chill_activitybundle_activity_location", + ); if (value.onthefly) { const body = { - "type": "location", - "name": value.name === '__AccompanyingCourseLocation__' ? null : value.name, - "locationType": { - "id": value.locationType.id, - "type": "location-type" - } + type: "location", + name: + value.name === "__AccompanyingCourseLocation__" ? null : value.name, + locationType: { + id: value.locationType.id, + type: "location-type", + }, }; if (value.address.id) { Object.assign(body, { - "address": { - "id": value.address.id + address: { + id: value.address.id, }, - }) + }); } postLocation(body) - .then( - location => hiddenLocation.value = location.id - ).catch( - err => { + .then((location) => (hiddenLocation.value = location.id)) + .catch((err) => { console.log(err.message); - } - ); + }); } else { hiddenLocation.value = value.id; } commit("updateLocation", value); - } -} + }, +}; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/getters.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/getters.js index b9d9b6a82..c3b3a77fc 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/getters.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/getters.js @@ -18,7 +18,7 @@ export default { if (null === state.activity.start) { return new Date(); } - throw 'transform date to object ?'; + throw "transform date to object ?"; }, /** * Compute the event sources to show on the FullCalendar @@ -33,7 +33,7 @@ export default { // current calendar if (state.activity.startDate !== null && state.activity.endDate !== null) { const s = { - id: 'current', + id: "current", events: [ { title: "Rendez-vous", @@ -41,8 +41,8 @@ export default { end: state.activity.endDate, allDay: false, is: "current", - classNames: ['iscurrent'], - } + classNames: ["iscurrent"], + }, ], editable: state.activity.calendarRange === null, }; @@ -52,7 +52,7 @@ export default { for (const [userId, kinds] of state.currentView.users.entries()) { if (!state.usersData.has(userId)) { - console.log('try to get events on a user which not exists', userId); + console.log("try to get events on a user which not exists", userId); continue; } @@ -61,11 +61,16 @@ export default { if (kinds.ranges && userData.calendarRanges.length > 0) { const s = { id: `ranges_${userId}`, - events: userData.calendarRanges.filter(r => state.activity.calendarRange === null || r.calendarRangeId !== state.activity.calendarRange.calendarRangeId), + events: userData.calendarRanges.filter( + (r) => + state.activity.calendarRange === null || + r.calendarRangeId !== + state.activity.calendarRange.calendarRangeId, + ), color: userData.mainColor, - classNames: ['isrange'], - backgroundColor: 'white', - textColor: 'black', + classNames: ["isrange"], + backgroundColor: "white", + textColor: "black", editable: false, }; @@ -74,10 +79,10 @@ export default { if (kinds.remotes && userData.remotes.length > 0) { const s = { - 'id': `remote_${userId}`, + id: `remote_${userId}`, events: userData.remotes, color: userData.mainColor, - textColor: 'black', + textColor: "black", editable: false, }; @@ -87,10 +92,12 @@ export default { // if remotes is checked, we display also the locals calendars if (kinds.remotes && userData.locals.length > 0) { const s = { - 'id': `local_${userId}`, - events: userData.locals.filter(l => l.originId !== state.activity.id), + id: `local_${userId}`, + events: userData.locals.filter( + (l) => l.originId !== state.activity.id, + ), color: userData.mainColor, - textColor: 'black', + textColor: "black", editable: false, }; @@ -104,7 +111,7 @@ export default { return state.activity.startDate; }, getInviteForUser: (state) => (user) => { - return state.activity.invites.find(i => i.user.id === user.id); + return state.activity.invites.find((i) => i.user.id === user.id); }, /** * get the user data for a specific user @@ -138,19 +145,21 @@ export default { * @param getters * @returns {(function({user: *, start: *, end: *}): (boolean))|*} */ - isCalendarRangeLoadedForUser: (state, getters) => ({user, start, end}) => { - if (!getters.hasUserData(user)) { - return false; - } - - for (let interval of getters.getUserData(user).calendarRangesLoaded) { - if (start >= interval.start && end <= interval.end) { - return true; + isCalendarRangeLoadedForUser: + (state, getters) => + ({ user, start, end }) => { + if (!getters.hasUserData(user)) { + return false; } - } - return false; - }, + for (let interval of getters.getUserData(user).calendarRangesLoaded) { + if (start >= interval.start && end <= interval.end) { + return true; + } + } + + return false; + }, /** * return true if there was a fetch query for event between this date (start and end), * those date are included. @@ -159,19 +168,21 @@ export default { * @param getters * @returns {(function({user: *, start: *, end: *}): (boolean))|*} */ - isCalendarRemoteLoadedForUser: (state, getters) => ({user, start, end}) => { - if (!getters.hasUserData(user)) { - return false; - } - - for (let interval of getters.getUserData(user).remotesLoaded) { - if (start >= interval.start && end <= interval.end) { - return true; + isCalendarRemoteLoadedForUser: + (state, getters) => + ({ user, start, end }) => { + if (!getters.hasUserData(user)) { + return false; } - } - return false; - }, + for (let interval of getters.getUserData(user).remotesLoaded) { + if (start >= interval.start && end <= interval.end) { + return true; + } + } + + return false; + }, /** * return true if the user ranges are shown on calendar * @@ -180,8 +191,10 @@ export default { */ isRangeShownOnCalendarForUser: (state) => (user) => { const k = state.currentView.users.get(user.id); - if (typeof k === 'undefined') { - console.error('try to determinate if calendar range is shown and user is not in currentView'); + if (typeof k === "undefined") { + console.error( + "try to determinate if calendar range is shown and user is not in currentView", + ); return false; } @@ -195,8 +208,10 @@ export default { */ isRemoteShownOnCalendarForUser: (state) => (user) => { const k = state.currentView.users.get(user.id); - if (typeof k === 'undefined') { - console.error('try to determinate if calendar range is shown and user is not in currentView'); + if (typeof k === "undefined") { + console.error( + "try to determinate if calendar range is shown and user is not in currentView", + ); return false; } @@ -205,8 +220,8 @@ export default { getLocationById: (state) => (id) => { for (let group of state.availableLocations) { - console.log('group', group); - const found = group.locations.find(l => l.id === id); + console.log("group", group); + const found = group.locations.find((l) => l.id === id); if (typeof found !== "undefined") { return found; } @@ -216,57 +231,60 @@ export default { }, suggestedEntities(state, getters) { - if (typeof (state.activity.accompanyingPeriod) === 'undefined') { + if (typeof state.activity.accompanyingPeriod === "undefined") { return []; } const allEntities = [ ...getters.suggestedPersons, ...getters.suggestedRequestor, ...getters.suggestedUser, - ...getters.suggestedResources + ...getters.suggestedResources, ]; - const uniqueIds = [...new Set(allEntities.map(i => `${i.type}-${i.id}`))]; - return Array.from(uniqueIds, id => allEntities.filter(r => `${r.type}-${r.id}` === id)[0]); + const uniqueIds = [...new Set(allEntities.map((i) => `${i.type}-${i.id}`))]; + return Array.from( + uniqueIds, + (id) => allEntities.filter((r) => `${r.type}-${r.id}` === id)[0], + ); }, suggestedPersons(state) { - const existingPersonIds = state.activity.persons.map(p => p.id); + const existingPersonIds = state.activity.persons.map((p) => p.id); return state.activity.accompanyingPeriod.participations - .filter(p => p.endDate === null) - .map(p => p.person) - .filter(p => !existingPersonIds.includes(p.id)) + .filter((p) => p.endDate === null) + .map((p) => p.person) + .filter((p) => !existingPersonIds.includes(p.id)); }, suggestedRequestor(state) { if (state.activity.accompanyingPeriod.requestor === null) { return []; } - const existingPersonIds = state.activity.persons.map(p => p.id); - const existingThirdPartyIds = state.activity.thirdParties.map(p => p.id); - return [state.activity.accompanyingPeriod.requestor] - .filter(r => - (r.type === 'person' && !existingPersonIds.includes(r.id)) || - (r.type === 'thirdparty' && !existingThirdPartyIds.includes(r.id)) - ); + const existingPersonIds = state.activity.persons.map((p) => p.id); + const existingThirdPartyIds = state.activity.thirdParties.map((p) => p.id); + return [state.activity.accompanyingPeriod.requestor].filter( + (r) => + (r.type === "person" && !existingPersonIds.includes(r.id)) || + (r.type === "thirdparty" && !existingThirdPartyIds.includes(r.id)), + ); }, suggestedUser(state) { if (null === state.activity.users) { return []; } - const existingUserIds = state.activity.users.map(p => p.id); - return [state.activity.accompanyingPeriod.user] - .filter( - u => u !== null && !existingUserIds.includes(u.id) - ); + const existingUserIds = state.activity.users.map((p) => p.id); + return [state.activity.accompanyingPeriod.user].filter( + (u) => u !== null && !existingUserIds.includes(u.id), + ); }, suggestedResources(state) { const resources = state.activity.accompanyingPeriod.resources; - const existingPersonIds = state.activity.persons.map(p => p.id); - const existingThirdPartyIds = state.activity.thirdParties.map(p => p.id); + const existingPersonIds = state.activity.persons.map((p) => p.id); + const existingThirdPartyIds = state.activity.thirdParties.map((p) => p.id); return state.activity.accompanyingPeriod.resources - .map(r => r.resource) - .filter(r => - (r.type === 'person' && !existingPersonIds.includes(r.id)) || - (r.type === 'thirdparty' && !existingThirdPartyIds.includes(r.id)) + .map((r) => r.resource) + .filter( + (r) => + (r.type === "person" && !existingPersonIds.includes(r.id)) || + (r.type === "thirdparty" && !existingThirdPartyIds.includes(r.id)), ); - } -} + }, +}; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/index.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/index.js index ffb186cdf..ec7886840 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/index.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/index.js @@ -1,57 +1,65 @@ -import 'es6-promise/auto'; -import { createStore } from 'vuex'; -import { postLocation } from 'ChillActivityAssets/vuejs/Activity/api'; -import getters from './getters'; -import actions from './actions'; -import mutations from './mutations'; -import { mapEntity } from './utils'; -import { whoami } from '../api'; +import "es6-promise/auto"; +import { createStore } from "vuex"; +import { postLocation } from "ChillActivityAssets/vuejs/Activity/api"; +import getters from "./getters"; +import actions from "./actions"; +import mutations from "./mutations"; +import { mapEntity } from "./utils"; +import { whoami } from "../api"; import prepareLocations from "ChillActivityAssets/vuejs/Activity/store.locations"; -const debug = process.env.NODE_ENV !== 'production'; +const debug = process.env.NODE_ENV !== "production"; const store = createStore({ - strict: debug, - state: { - activity: mapEntity(window.entity), // activity is the calendar entity actually - currentEvent: null, - availableLocations: [], - /** - * the current user - */ - me: null, - /** - * store information about current view - */ - currentView: { - start: null, - end: null, - users: new Map(), - }, - /** - * store a list of existing event, to avoid storing them twice - */ - existingEvents: new Set(), - /** - * store user data - */ - usersData: new Map(), - }, - getters, - mutations, - actions, + strict: debug, + state: { + activity: mapEntity(window.entity), // activity is the calendar entity actually + currentEvent: null, + availableLocations: [], + /** + * the current user + */ + me: null, + /** + * store information about current view + */ + currentView: { + start: null, + end: null, + users: new Map(), + }, + /** + * store a list of existing event, to avoid storing them twice + */ + existingEvents: new Set(), + /** + * store user data + */ + usersData: new Map(), + }, + getters, + mutations, + actions, }); -whoami().then(me => { - store.commit('setWhoAmiI', me); +whoami().then((me) => { + store.commit("setWhoAmiI", me); }); if (null !== store.getters.getMainUser) { - store.commit('showUserOnCalendar', {ranges: true, remotes: true, user: store.getters.getMainUser}); + store.commit("showUserOnCalendar", { + ranges: true, + remotes: true, + user: store.getters.getMainUser, + }); } for (let u of store.state.activity.users) { - store.commit('showUserOnCalendar', {ranges: false, remotes: false, user: u}); + store.commit("showUserOnCalendar", { + ranges: false, + remotes: false, + user: u, + }); } prepareLocations(store); diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/mutations.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/mutations.js index c956b0d87..17ebd6142 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/mutations.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/mutations.js @@ -3,30 +3,27 @@ import { calendarRangeToFullCalendarEvent, remoteToFullCalendarEvent, localsToFullCalendarEvent, -} from './utils'; +} from "./utils"; export default { setWhoAmiI(state, me) { state.me = me; }, - setCurrentDatesView(state, {start, end}) { + setCurrentDatesView(state, { start, end }) { state.currentView.start = start; state.currentView.end = end; }, - showUserOnCalendar(state, {user, ranges, remotes}) { + showUserOnCalendar(state, { user, ranges, remotes }) { if (!state.usersData.has(user.id)) { state.usersData.set(user.id, createUserData(user, state.usersData.size)); } const cur = state.currentView.users.get(user.id); - state.currentView.users.set( - user.id, - { - ranges: typeof ranges !== 'undefined' ? ranges : cur.ranges, - remotes: typeof remotes !== 'undefined' ? remotes : cur.remotes, - } - ); + state.currentView.users.set(user.id, { + ranges: typeof ranges !== "undefined" ? ranges : cur.ranges, + remotes: typeof remotes !== "undefined" ? remotes : cur.remotes, + }); }, /** * Set the event start and end to the given start and end, @@ -36,7 +33,7 @@ export default { * @param Date start * @param Date end */ - setEventTimes(state, {start, end}) { + setEventTimes(state, { start, end }) { state.activity.startDate = start; state.activity.endDate = end; state.activity.calendarRange = null; @@ -48,8 +45,8 @@ export default { * @param state * @param range */ - associateCalendarToRange(state, {range}) { - console.log('associateCalendarToRange', range); + associateCalendarToRange(state, { range }) { + console.log("associateCalendarToRange", range); if (null === range) { state.activity.calendarRange = null; @@ -59,22 +56,25 @@ export default { return; } - console.log('userId', range.extendedProps.userId); + console.log("userId", range.extendedProps.userId); - const r = state.usersData.get(range.extendedProps.userId).calendarRanges - .find(r => r.calendarRangeId === range.extendedProps.calendarRangeId); + const r = state.usersData + .get(range.extendedProps.userId) + .calendarRanges.find( + (r) => r.calendarRangeId === range.extendedProps.calendarRangeId, + ); - if (typeof r === 'undefined') { - throw Error('Could not find managed calendar range'); + if (typeof r === "undefined") { + throw Error("Could not find managed calendar range"); } - console.log('range found', r); + console.log("range found", r); state.activity.startDate = range.start; state.activity.endDate = range.end; state.activity.calendarRange = r; - console.log('activity', state.activity); + console.log("activity", state.activity); }, setMainUser(state, user) { @@ -85,32 +85,36 @@ export default { addPersonsInvolved(state, payload) { //console.log('### mutation addPersonsInvolved', payload.result.type); switch (payload.result.type) { - case 'person': + case "person": state.activity.persons.push(payload.result); break; - case 'thirdparty': + case "thirdparty": state.activity.thirdParties.push(payload.result); break; - case 'user': + case "user": state.activity.users.push(payload.result); break; } - ; }, removePersonInvolved(state, payload) { //console.log('### mutation removePersonInvolved', payload.type); switch (payload.type) { - case 'person': - state.activity.persons = state.activity.persons.filter(person => person !== payload); + case "person": + state.activity.persons = state.activity.persons.filter( + (person) => person !== payload, + ); break; - case 'thirdparty': - state.activity.thirdParties = state.activity.thirdParties.filter(thirdparty => thirdparty !== payload); + case "thirdparty": + state.activity.thirdParties = state.activity.thirdParties.filter( + (thirdparty) => thirdparty !== payload, + ); break; - case 'user': - state.activity.users = state.activity.users.filter(user => user !== payload); + case "user": + state.activity.users = state.activity.users.filter( + (user) => user !== payload, + ); break; } - ; }, /** * Add CalendarRange object for an user @@ -121,7 +125,7 @@ export default { * @param start * @param end */ - addCalendarRangesForUser(state, {user, ranges, start, end}) { + addCalendarRangesForUser(state, { user, ranges, start, end }) { let userData; if (state.usersData.has(user.id)) { userData = state.usersData.get(user.id); @@ -131,18 +135,18 @@ export default { } const eventRanges = ranges - .filter(r => !state.existingEvents.has(`range_${r.id}`)) - .map(r => { + .filter((r) => !state.existingEvents.has(`range_${r.id}`)) + .map((r) => { // add to existing ids state.existingEvents.add(`range_${r.id}`); return r; }) - .map(r => calendarRangeToFullCalendarEvent(r)); + .map((r) => calendarRangeToFullCalendarEvent(r)); userData.calendarRanges = userData.calendarRanges.concat(eventRanges); - userData.calendarRangesLoaded.push({start, end}); + userData.calendarRangesLoaded.push({ start, end }); }, - addCalendarRemotesForUser(state, {user, remotes, start, end}) { + addCalendarRemotesForUser(state, { user, remotes, start, end }) { let userData; if (state.usersData.has(user.id)) { userData = state.usersData.get(user.id); @@ -152,18 +156,18 @@ export default { } const eventRemotes = remotes - .filter(r => !state.existingEvents.has(`remote_${r.id}`)) - .map(r => { + .filter((r) => !state.existingEvents.has(`remote_${r.id}`)) + .map((r) => { // add to existing ids state.existingEvents.add(`remote_${r.id}`); return r; }) - .map(r => remoteToFullCalendarEvent(r)); + .map((r) => remoteToFullCalendarEvent(r)); userData.remotes = userData.remotes.concat(eventRemotes); - userData.remotesLoaded.push({start, end}); + userData.remotesLoaded.push({ start, end }); }, - addCalendarLocalsForUser(state, {user, locals, start, end}) { + addCalendarLocalsForUser(state, { user, locals, start, end }) { let userData; if (state.usersData.has(user.id)) { userData = state.usersData.get(user.id); @@ -173,20 +177,20 @@ export default { } const eventRemotes = locals - .filter(r => !state.existingEvents.has(`locals_${r.id}`)) - .map(r => { + .filter((r) => !state.existingEvents.has(`locals_${r.id}`)) + .map((r) => { // add to existing ids state.existingEvents.add(`locals_${r.id}`); return r; }) - .map(r => localsToFullCalendarEvent(r)); + .map((r) => localsToFullCalendarEvent(r)); userData.locals = userData.locals.concat(eventRemotes); - userData.localsLoaded.push({start, end}); + userData.localsLoaded.push({ start, end }); }, // Location updateLocation(state, value) { - console.log('### mutation: updateLocation', value); + console.log("### mutation: updateLocation", value); state.activity.location = value; }, addAvailableLocationGroup(state, group) { diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/utils.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/utils.ts index 7bdb3b408..4e8f97e33 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/utils.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Calendar/store/utils.ts @@ -1,108 +1,117 @@ -import {COLORS} from '../const'; -import {ISOToDatetime} from '../../../../../../ChillMainBundle/Resources/public/chill/js/date'; -import {DateTime, User} from '../../../../../../ChillMainBundle/Resources/public/types'; -import {CalendarLight, CalendarRange, CalendarRemote} from '../../../types'; -import type {EventInputCalendarRange} from '../../../types'; -import {EventInput} from '@fullcalendar/core'; +import { COLORS } from "../const"; +import { ISOToDatetime } from "../../../../../../ChillMainBundle/Resources/public/chill/js/date"; +import { + DateTime, + User, +} from "../../../../../../ChillMainBundle/Resources/public/types"; +import { CalendarLight, CalendarRange, CalendarRemote } from "../../../types"; +import type { EventInputCalendarRange } from "../../../types"; +import { EventInput } from "@fullcalendar/core"; export interface UserData { - user: User, - calendarRanges: CalendarRange[], - calendarRangesLoaded: {}[], - remotes: CalendarRemote[], - remotesLoaded: {}[], - locals: CalendarRemote[], - localsLoaded: {}[], - mainColor: string, + user: User; + calendarRanges: CalendarRange[]; + calendarRangesLoaded: {}[]; + remotes: CalendarRemote[]; + remotesLoaded: {}[]; + locals: CalendarRemote[]; + localsLoaded: {}[]; + mainColor: string; } export const addIdToValue = (string: string, id: number): string => { - const array = string ? string.split(',') : []; - array.push(id.toString()); - const str = array.join(); - return str; + const array = string ? string.split(",") : []; + array.push(id.toString()); + const str = array.join(); + return str; }; export const removeIdFromValue = (string: string, id: number) => { - let array = string.split(','); - array = array.filter(el => el !== id.toString()); - const str = array.join(); - return str; + let array = string.split(","); + array = array.filter((el) => el !== id.toString()); + const str = array.join(); + return str; }; /* -* Assign missing keys for the ConcernedGroups component -*/ + * Assign missing keys for the ConcernedGroups component + */ export const mapEntity = (entity: EventInput): EventInput => { - const calendar = { ...entity}; - Object.assign(calendar, {thirdParties: entity.professionals}); + const calendar = { ...entity }; + Object.assign(calendar, { thirdParties: entity.professionals }); - if (entity.startDate !== null ) { - calendar.startDate = ISOToDatetime(entity.startDate.datetime); - } - if (entity.endDate !== null) { - calendar.endDate = ISOToDatetime(entity.endDate.datetime); - } + if (entity.startDate !== null) { + calendar.startDate = ISOToDatetime(entity.startDate.datetime); + } + if (entity.endDate !== null) { + calendar.endDate = ISOToDatetime(entity.endDate.datetime); + } - if (entity.calendarRange !== null) { - calendar.calendarRange.calendarRangeId = entity.calendarRange.id; - calendar.calendarRange.id = `range_${entity.calendarRange.id}`; - } + if (entity.calendarRange !== null) { + calendar.calendarRange.calendarRangeId = entity.calendarRange.id; + calendar.calendarRange.id = `range_${entity.calendarRange.id}`; + } - return calendar; + return calendar; }; -export const createUserData = (user: User, colorIndex: number): UserData => { - const colorId = colorIndex % COLORS.length; +export const createUserData = (user: User, colorIndex: number): UserData => { + const colorId = colorIndex % COLORS.length; - return { - user: user, - calendarRanges: [], - calendarRangesLoaded: [], - remotes: [], - remotesLoaded: [], - locals: [], - localsLoaded: [], - mainColor: COLORS[colorId], - } -} + return { + user: user, + calendarRanges: [], + calendarRangesLoaded: [], + remotes: [], + remotesLoaded: [], + locals: [], + localsLoaded: [], + mainColor: COLORS[colorId], + }; +}; // TODO move this function to a more global namespace, as it is also in use in MyCalendarRange app -export const calendarRangeToFullCalendarEvent = (entity: CalendarRange): EventInputCalendarRange => { - return { - id: `range_${entity.id}`, - title: "(" + entity.user.text + ")", - start: entity.startDate.datetime8601, - end: entity.endDate.datetime8601, - allDay: false, - userId: entity.user.id, - userLabel: entity.user.label, - calendarRangeId: entity.id, - locationId: entity.location.id, - locationName: entity.location.name, - is: 'range', - }; -} +export const calendarRangeToFullCalendarEvent = ( + entity: CalendarRange, +): EventInputCalendarRange => { + return { + id: `range_${entity.id}`, + title: "(" + entity.user.text + ")", + start: entity.startDate.datetime8601, + end: entity.endDate.datetime8601, + allDay: false, + userId: entity.user.id, + userLabel: entity.user.label, + calendarRangeId: entity.id, + locationId: entity.location.id, + locationName: entity.location.name, + is: "range", + }; +}; -export const remoteToFullCalendarEvent = (entity: CalendarRemote): EventInput & {id: string} => { - return { - id: `range_${entity.id}`, - title: entity.title, - start: entity.startDate.datetime8601, - end: entity.endDate.datetime8601, - allDay: entity.isAllDay, - is: 'remote', - }; -} +export const remoteToFullCalendarEvent = ( + entity: CalendarRemote, +): EventInput & { id: string } => { + return { + id: `range_${entity.id}`, + title: entity.title, + start: entity.startDate.datetime8601, + end: entity.endDate.datetime8601, + allDay: entity.isAllDay, + is: "remote", + }; +}; -export const localsToFullCalendarEvent = (entity: CalendarLight): EventInput & {id: string; originId: number;} => { - return { - id: `local_${entity.id}`, - title: entity.persons.map(p => p.text).join(', '), - originId: entity.id, - start: entity.startDate.datetime8601, - end: entity.endDate.datetime8601, - allDay: false, - is: 'local', - }; -} +export const localsToFullCalendarEvent = ( + entity: CalendarLight, +): EventInput & { id: string; originId: number } => { + return { + id: `local_${entity.id}`, + title: entity.persons.map((p) => p.text).join(", "), + originId: entity.id, + start: entity.startDate.datetime8601, + end: entity.endDate.datetime8601, + allDay: false, + is: "local", + }; +}; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Invite/Answer.vue b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Invite/Answer.vue index 4607af7fc..34b5e3d77 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Invite/Answer.vue +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/Invite/Answer.vue @@ -1,95 +1,133 @@ - - + diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/App2.vue b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/App2.vue index 4de668e91..51db83873 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/App2.vue +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/App2.vue @@ -1,180 +1,225 @@ diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/Components/EditLocation.vue b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/Components/EditLocation.vue index 82c8cf86a..86d4a6c5a 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/Components/EditLocation.vue +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/Components/EditLocation.vue @@ -1,49 +1,46 @@ - + diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/i18n.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/i18n.ts index 4c910aa87..e9e31dd25 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/i18n.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/i18n.ts @@ -1,28 +1,27 @@ const appMessages = { - fr: { - created_availabilities: "Lieu des plages de disponibilités créées", - edit_your_calendar_range: "Planifiez vos plages de disponibilités", - show_my_calendar: "Afficher mon calendrier", - show_weekends: "Afficher les week-ends", - copy_range: "Copier", - copy_range_from_to: "Copier les plages", - from_day_to_day: "d'un jour à l'autre", - from_week_to_week: "d'une semaine à l'autre", - copy_range_how_to: "Créez les plages de disponibilités durant une journée et copiez-les facilement au jour suivant avec ce bouton. Si les week-ends sont cachés, le jour suivant un vendredi sera le lundi.", - new_range_to_save: "Nouvelles plages à enregistrer", - update_range_to_save: "Plages à modifier", - delete_range_to_save: "Plages à supprimer", - by: "Par", - main_user_concerned: "Utilisateur concerné", - dateFrom: "De", - dateTo: "à", - day: "Jour", - week: "Semaine", - month: "Mois", - today: "Aujourd'hui", - } -} - -export { - appMessages + fr: { + created_availabilities: "Lieu des plages de disponibilités créées", + edit_your_calendar_range: "Planifiez vos plages de disponibilités", + show_my_calendar: "Afficher mon calendrier", + show_weekends: "Afficher les week-ends", + copy_range: "Copier", + copy_range_from_to: "Copier les plages", + from_day_to_day: "d'un jour à l'autre", + from_week_to_week: "d'une semaine à l'autre", + copy_range_how_to: + "Créez les plages de disponibilités durant une journée et copiez-les facilement au jour suivant avec ce bouton. Si les week-ends sont cachés, le jour suivant un vendredi sera le lundi.", + new_range_to_save: "Nouvelles plages à enregistrer", + update_range_to_save: "Plages à modifier", + delete_range_to_save: "Plages à supprimer", + by: "Par", + main_user_concerned: "Utilisateur concerné", + dateFrom: "De", + dateTo: "à", + day: "Jour", + week: "Semaine", + month: "Mois", + today: "Aujourd'hui", + }, }; + +export { appMessages }; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/index2.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/index2.ts index 52dcd318d..cb87b0b67 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/index2.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/index2.ts @@ -1,19 +1,19 @@ -import { createApp } from 'vue'; -import { _createI18n } from '../../../../../ChillMainBundle/Resources/public/vuejs/_js/i18n' -import { appMessages } from './i18n' -import futureStore, {key} from './store/index' +import { createApp } from "vue"; +import { _createI18n } from "../../../../../ChillMainBundle/Resources/public/vuejs/_js/i18n"; +import { appMessages } from "./i18n"; +import futureStore, { key } from "./store/index"; -import App2 from './App2.vue'; -import {useI18n} from "vue-i18n"; +import App2 from "./App2.vue"; +import { useI18n } from "vue-i18n"; futureStore().then((store) => { - const i18n = _createI18n(appMessages, false); + const i18n = _createI18n(appMessages, false); - const app = createApp({ - template: ``, - }) - .use(store, key) - .use(i18n) - .component('app', App2) - .mount('#myCalendar'); + const app = createApp({ + template: ``, + }) + .use(store, key) + .use(i18n) + .component("app", App2) + .mount("#myCalendar"); }); diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/index.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/index.ts index f87832cb5..e5a863245 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/index.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/index.ts @@ -1,50 +1,56 @@ -import 'es6-promise/auto'; -import {Store, createStore} from 'vuex'; -import {InjectionKey} from "vue"; -import me, {MeState} from './modules/me'; -import fullCalendar, {FullCalendarState} from './modules/fullcalendar'; -import calendarRanges, {CalendarRangesState} from './modules/calendarRanges'; -import calendarRemotes, {CalendarRemotesState} from './modules/calendarRemotes'; -import {whoami} from "../../../../../../ChillMainBundle/Resources/public/lib/api/user"; -import {User} from '../../../../../../ChillMainBundle/Resources/public/types'; -import locations, {LocationState} from "./modules/location"; -import calendarLocals, {CalendarLocalsState} from "./modules/calendarLocals"; +import "es6-promise/auto"; +import { Store, createStore } from "vuex"; +import { InjectionKey } from "vue"; +import me, { MeState } from "./modules/me"; +import fullCalendar, { FullCalendarState } from "./modules/fullcalendar"; +import calendarRanges, { CalendarRangesState } from "./modules/calendarRanges"; +import calendarRemotes, { + CalendarRemotesState, +} from "./modules/calendarRemotes"; +import { whoami } from "../../../../../../ChillMainBundle/Resources/public/lib/api/user"; +import { User } from "../../../../../../ChillMainBundle/Resources/public/types"; +import locations, { LocationState } from "./modules/location"; +import calendarLocals, { CalendarLocalsState } from "./modules/calendarLocals"; -const debug = process.env.NODE_ENV !== 'production'; +const debug = process.env.NODE_ENV !== "production"; export interface State { - calendarRanges: CalendarRangesState, - calendarRemotes: CalendarRemotesState, - calendarLocals: CalendarLocalsState, - fullCalendar: FullCalendarState, - me: MeState, - locations: LocationState + calendarRanges: CalendarRangesState; + calendarRemotes: CalendarRemotesState; + calendarLocals: CalendarLocalsState; + fullCalendar: FullCalendarState; + me: MeState; + locations: LocationState; } export const key: InjectionKey> = Symbol(); -const futureStore = function(): Promise> { - return whoami().then((user: User) => { - const store = createStore({ - strict: debug, - modules: { - me, - fullCalendar, - calendarRanges, - calendarRemotes, - calendarLocals, - locations, - }, - mutations: {} - }); +const futureStore = function (): Promise> { + return whoami().then((user: User) => { + const store = createStore({ + strict: debug, + modules: { + me, + fullCalendar, + calendarRanges, + calendarRemotes, + calendarLocals, + locations, + }, + mutations: {}, + }); - store.commit('me/setWhoAmi', user, {root: true}); - store.dispatch('locations/getLocations', null, {root: true}).then(_ => { - return store.dispatch('locations/getCurrentLocation', null, {root: true}); - }); + store.commit("me/setWhoAmi", user, { root: true }); + store + .dispatch("locations/getLocations", null, { root: true }) + .then((_) => { + return store.dispatch("locations/getCurrentLocation", null, { + root: true, + }); + }); - return Promise.resolve(store); - }); -} + return Promise.resolve(store); + }); +}; export default futureStore; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarLocals.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarLocals.ts index c5422c97e..07ce477dd 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarLocals.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarLocals.ts @@ -1,95 +1,116 @@ -import {State} from './../index'; -import {ActionContext, Module} from 'vuex'; -import {CalendarLight} from '../../../../types'; -import {fetchCalendarLocalForUser} from '../../../Calendar/api'; -import {EventInput} from '@fullcalendar/core'; -import {localsToFullCalendarEvent} from "../../../Calendar/store/utils"; -import {TransportExceptionInterface} from "../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods"; -import {COLORS} from "../../../Calendar/const"; +import { State } from "./../index"; +import { ActionContext, Module } from "vuex"; +import { CalendarLight } from "../../../../types"; +import { fetchCalendarLocalForUser } from "../../../Calendar/api"; +import { EventInput } from "@fullcalendar/core"; +import { localsToFullCalendarEvent } from "../../../Calendar/store/utils"; +import { TransportExceptionInterface } from "../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods"; +import { COLORS } from "../../../Calendar/const"; export interface CalendarLocalsState { - locals: EventInput[], - localsLoaded: {start: number, end: number}[], - localsIndex: Set, - key: number + locals: EventInput[]; + localsLoaded: { start: number; end: number }[]; + localsIndex: Set; + key: number; } type Context = ActionContext; export default { - namespaced: true, - state: (): CalendarLocalsState => ({ - locals: [], - localsLoaded: [], - localsIndex: new Set(), - key: 0 - }), - getters: { - isLocalsLoaded: (state: CalendarLocalsState) => ({start, end}: {start: Date, end: Date}): boolean => { - for (const range of state.localsLoaded) { - if (start.getTime() === range.start && end.getTime() === range.end) { - return true; - } - } + namespaced: true, + state: (): CalendarLocalsState => ({ + locals: [], + localsLoaded: [], + localsIndex: new Set(), + key: 0, + }), + getters: { + isLocalsLoaded: + (state: CalendarLocalsState) => + ({ start, end }: { start: Date; end: Date }): boolean => { + for (const range of state.localsLoaded) { + if ( + start.getTime() === range.start && + end.getTime() === range.end + ) { + return true; + } + } - return false; + return false; + }, }, - }, - mutations: { - addLocals(state: CalendarLocalsState, ranges: CalendarLight[]) { - console.log('addLocals', ranges); + mutations: { + addLocals(state: CalendarLocalsState, ranges: CalendarLight[]) { + console.log("addLocals", ranges); - const toAdd = ranges - .map(cr => localsToFullCalendarEvent(cr)) - .filter(r => !state.localsIndex.has(r.id)); + const toAdd = ranges + .map((cr) => localsToFullCalendarEvent(cr)) + .filter((r) => !state.localsIndex.has(r.id)); - toAdd.forEach((r) => { - state.localsIndex.add(r.id); - state.locals.push(r); - }); - state.key = state.key + toAdd.length; + toAdd.forEach((r) => { + state.localsIndex.add(r.id); + state.locals.push(r); + }); + state.key = state.key + toAdd.length; + }, + addLoaded( + state: CalendarLocalsState, + payload: { start: Date; end: Date }, + ) { + state.localsLoaded.push({ + start: payload.start.getTime(), + end: payload.end.getTime(), + }); + }, }, - addLoaded(state: CalendarLocalsState, payload: {start: Date, end: Date}) { - state.localsLoaded.push({start: payload.start.getTime(), end: payload.end.getTime()}); + actions: { + fetchLocals( + ctx: Context, + payload: { start: Date; end: Date }, + ): Promise { + const start = payload.start; + const end = payload.end; + + if (ctx.rootGetters["me/getMe"] === null) { + return Promise.resolve(null); + } + + if (ctx.getters.isLocalsLoaded({ start, end })) { + return Promise.resolve(ctx.getters.getRangeSource); + } + + ctx.commit("addLoaded", { + start: start, + end: end, + }); + + return fetchCalendarLocalForUser( + ctx.rootGetters["me/getMe"], + start, + end, + ) + .then((remotes: CalendarLight[]) => { + // to be add when reactivity problem will be solve ? + //ctx.commit('addRemotes', remotes); + const inputs = remotes + .map((cr) => localsToFullCalendarEvent(cr)) + .map((cr) => ({ + ...cr, + backgroundColor: COLORS[0], + textColor: "black", + editable: false, + })); + ctx.commit("calendarRanges/addExternals", inputs, { + root: true, + }); + return Promise.resolve(null); + }) + .catch((e: TransportExceptionInterface) => { + console.error(e); + + return Promise.resolve(null); + }); + }, }, - }, - actions: { - fetchLocals(ctx: Context, payload: {start: Date, end: Date}): Promise { - const start = payload.start; - const end = payload.end; - - if (ctx.rootGetters['me/getMe'] === null) { - return Promise.resolve(null); - } - - if (ctx.getters.isLocalsLoaded({start, end})) { - return Promise.resolve(ctx.getters.getRangeSource); - } - - ctx.commit('addLoaded', { - start: start, - end: end, - }); - - return fetchCalendarLocalForUser( - ctx.rootGetters['me/getMe'], - start, - end - ) - .then((remotes: CalendarLight[]) => { - // to be add when reactivity problem will be solve ? - //ctx.commit('addRemotes', remotes); - const inputs = remotes - .map(cr => localsToFullCalendarEvent(cr)) - .map(cr => ({...cr, backgroundColor: COLORS[0], textColor: 'black', editable: false})) - ctx.commit('calendarRanges/addExternals', inputs, {root: true}); - return Promise.resolve(null); - }) - .catch((e: TransportExceptionInterface) => { - console.error(e); - - return Promise.resolve(null); - }); - } - } } as Module; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRanges.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRanges.ts index 00bf1e86d..5d1876d05 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRanges.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRanges.ts @@ -1,286 +1,377 @@ -import {State} from './../index'; -import {ActionContext, Module} from 'vuex'; -import {CalendarRange, CalendarRangeCreate, CalendarRangeEdit, isEventInputCalendarRange} from "../../../../types"; -import {Location} from "../../../../../../../ChillMainBundle/Resources/public/types"; -import {fetchCalendarRangeForUser} from '../../../Calendar/api'; -import {calendarRangeToFullCalendarEvent} from '../../../Calendar/store/utils'; -import {EventInput} from '@fullcalendar/core'; -import {makeFetch} from "../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods"; +import { State } from "./../index"; +import { ActionContext, Module } from "vuex"; import { - datetimeToISO, - dateToISO, - ISOToDatetime + CalendarRange, + CalendarRangeCreate, + CalendarRangeEdit, + isEventInputCalendarRange, +} from "../../../../types"; +import { Location } from "../../../../../../../ChillMainBundle/Resources/public/types"; +import { fetchCalendarRangeForUser } from "../../../Calendar/api"; +import { calendarRangeToFullCalendarEvent } from "../../../Calendar/store/utils"; +import { EventInput } from "@fullcalendar/core"; +import { makeFetch } from "../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods"; +import { + datetimeToISO, + dateToISO, + ISOToDatetime, } from "../../../../../../../ChillMainBundle/Resources/public/chill/js/date"; -import type {EventInputCalendarRange} from "../../../../types"; +import type { EventInputCalendarRange } from "../../../../types"; export interface CalendarRangesState { - ranges: (EventInput | EventInputCalendarRange) [], - rangesLoaded: { start: number, end: number }[], - rangesIndex: Set, - key: number + ranges: (EventInput | EventInputCalendarRange)[]; + rangesLoaded: { start: number; end: number }[]; + rangesIndex: Set; + key: number; } type Context = ActionContext; export default { - namespaced: true, - state: (): CalendarRangesState => ({ - ranges: [], - rangesLoaded: [], - rangesIndex: new Set(), - key: 0 - }), - getters: { - isRangeLoaded: (state: CalendarRangesState) => ({start, end}: { start: Date, end: Date }): boolean => { - for (const range of state.rangesLoaded) { - if (start.getTime() === range.start && end.getTime() === range.end) { - return true; - } - } + namespaced: true, + state: (): CalendarRangesState => ({ + ranges: [], + rangesLoaded: [], + rangesIndex: new Set(), + key: 0, + }), + getters: { + isRangeLoaded: + (state: CalendarRangesState) => + ({ start, end }: { start: Date; end: Date }): boolean => { + for (const range of state.rangesLoaded) { + if ( + start.getTime() === range.start && + end.getTime() === range.end + ) { + return true; + } + } - return false; + return false; + }, + getRangesOnDate: + (state: CalendarRangesState) => + (date: Date): EventInputCalendarRange[] => { + const founds = []; + const dateStr = dateToISO(date) as string; + + for (const range of state.ranges) { + if ( + isEventInputCalendarRange(range) && + range.start.startsWith(dateStr) + ) { + founds.push(range); + } + } + + return founds; + }, + getRangesOnWeek: + (state: CalendarRangesState) => + (mondayDate: Date): EventInputCalendarRange[] => { + const founds = []; + for (const d of Array.from(Array(7).keys())) { + const dateOfWeek = new Date(mondayDate); + dateOfWeek.setDate(mondayDate.getDate() + d); + const dateStr = dateToISO(dateOfWeek) as string; + for (const range of state.ranges) { + if ( + isEventInputCalendarRange(range) && + range.start.startsWith(dateStr) + ) { + founds.push(range); + } + } + } + + return founds; + }, }, - getRangesOnDate: (state: CalendarRangesState) => (date: Date): EventInputCalendarRange[] => { - const founds = []; - const dateStr = dateToISO(date) as string; + mutations: { + addRanges(state: CalendarRangesState, ranges: CalendarRange[]) { + const toAdd = ranges + .map((cr) => calendarRangeToFullCalendarEvent(cr)) + .map((cr) => ({ + ...cr, + backgroundColor: "white", + borderColor: "#3788d8", + textColor: "black", + })) + .filter((r) => !state.rangesIndex.has(r.id)); - for (const range of state.ranges) { - if (isEventInputCalendarRange(range) - && range.start.startsWith(dateStr) + toAdd.forEach((r) => { + state.rangesIndex.add(r.id); + state.ranges.push(r); + }); + state.key = state.key + toAdd.length; + }, + addExternals(state, externalEvents: (EventInput & { id: string })[]) { + const toAdd = externalEvents.filter( + (r) => !state.rangesIndex.has(r.id), + ); + + toAdd.forEach((r) => { + state.rangesIndex.add(r.id); + state.ranges.push(r); + }); + state.key = state.key + toAdd.length; + }, + addLoaded( + state: CalendarRangesState, + payload: { start: Date; end: Date }, ) { - founds.push(range); - } - } - - return founds; - }, - getRangesOnWeek: (state: CalendarRangesState) => (mondayDate: Date): EventInputCalendarRange[] => { - const founds = []; - for (const d of Array.from(Array(7).keys())) { - const dateOfWeek = new Date(mondayDate); - dateOfWeek.setDate(mondayDate.getDate() + d); - const dateStr = dateToISO(dateOfWeek) as string; - for (const range of state.ranges) { - if (isEventInputCalendarRange(range) - && range.start.startsWith(dateStr) - ) { - founds.push(range); - } - } - } - - return founds; - }, - }, - mutations: { - addRanges(state: CalendarRangesState, ranges: CalendarRange[]) { - const toAdd = ranges - .map(cr => calendarRangeToFullCalendarEvent(cr)) - .map(cr => ({ - ...cr, backgroundColor: 'white', borderColor: '#3788d8', - textColor: 'black' - })) - .filter(r => !state.rangesIndex.has(r.id)); - - toAdd.forEach((r) => { - state.rangesIndex.add(r.id); - state.ranges.push(r); - }); - state.key = state.key + toAdd.length; - }, - addExternals(state, externalEvents: (EventInput & { id: string })[]) { - const toAdd = externalEvents - .filter(r => !state.rangesIndex.has(r.id)); - - toAdd.forEach((r) => { - state.rangesIndex.add(r.id); - state.ranges.push(r); - }); - state.key = state.key + toAdd.length; - }, - addLoaded(state: CalendarRangesState, payload: { start: Date, end: Date }) { - state.rangesLoaded.push({start: payload.start.getTime(), end: payload.end.getTime()}); - }, - addRange(state: CalendarRangesState, payload: CalendarRange) { - const asEvent = calendarRangeToFullCalendarEvent(payload); - state.ranges.push({...asEvent, backgroundColor: 'white', borderColor: '#3788d8', textColor: 'black'}); - state.rangesIndex.add(asEvent.id); - state.key = state.key + 1; - }, - removeRange(state: CalendarRangesState, calendarRangeId: number) { - const found = state.ranges.find(r => r.calendarRangeId === calendarRangeId && r.is === "range"); - - if (found !== undefined) { - state.ranges = state.ranges.filter( - (r) => !(r.calendarRangeId === calendarRangeId && r.is === "range") - ); - - if (typeof found.id === "string") { // should always be true - state.rangesIndex.delete(found.id); - } - - state.key = state.key + 1; - } - }, - updateRange(state, range: CalendarRange) { - const found = state.ranges.find(r => r.calendarRangeId === range.id && r.is === "range"); - const newEvent = calendarRangeToFullCalendarEvent(range); - - if (found !== undefined) { - found.start = newEvent.start; - found.end = newEvent.end; - found.locationId = range.location.id; - found.locationName = range.location.name; - } - - state.key = state.key + 1; - } - }, - actions: { - fetchRanges(ctx: Context, payload: { start: Date, end: Date }): Promise { - const start = payload.start; - const end = payload.end; - - if (ctx.rootGetters['me/getMe'] === null) { - return Promise.resolve(ctx.getters.getRangeSource); - } - - if (ctx.getters.isRangeLoaded({start, end})) { - return Promise.resolve(ctx.getters.getRangeSource); - } - - ctx.commit('addLoaded', { - start: start, - end: end, - }); - - return fetchCalendarRangeForUser( - ctx.rootGetters['me/getMe'], - start, - end - ) - .then((ranges: CalendarRange[]) => { - ctx.commit('addRanges', ranges); - return Promise.resolve(null); - }); - }, - createRange(ctx, {start, end, location}: { start: Date, end: Date, location: Location }): Promise { - const url = `/api/1.0/calendar/calendar-range.json?`; - - if (ctx.rootState.me.me === null) { - throw new Error('user is currently null'); - } - - const body = { - user: { - id: ctx.rootState.me.me.id, - type: "user" + state.rangesLoaded.push({ + start: payload.start.getTime(), + end: payload.end.getTime(), + }); }, - startDate: { - datetime: datetimeToISO(start), + addRange(state: CalendarRangesState, payload: CalendarRange) { + const asEvent = calendarRangeToFullCalendarEvent(payload); + state.ranges.push({ + ...asEvent, + backgroundColor: "white", + borderColor: "#3788d8", + textColor: "black", + }); + state.rangesIndex.add(asEvent.id); + state.key = state.key + 1; }, - endDate: { - datetime: datetimeToISO(end) + removeRange(state: CalendarRangesState, calendarRangeId: number) { + const found = state.ranges.find( + (r) => + r.calendarRangeId === calendarRangeId && r.is === "range", + ); + + if (found !== undefined) { + state.ranges = state.ranges.filter( + (r) => + !( + r.calendarRangeId === calendarRangeId && + r.is === "range" + ), + ); + + if (typeof found.id === "string") { + // should always be true + state.rangesIndex.delete(found.id); + } + + state.key = state.key + 1; + } }, - location: { - id: location.id, - type: "location" - } - } as CalendarRangeCreate; + updateRange(state, range: CalendarRange) { + const found = state.ranges.find( + (r) => r.calendarRangeId === range.id && r.is === "range", + ); + const newEvent = calendarRangeToFullCalendarEvent(range); - return makeFetch('POST', url, body) - .then((newRange) => { + if (found !== undefined) { + found.start = newEvent.start; + found.end = newEvent.end; + found.locationId = range.location.id; + found.locationName = range.location.name; + } - ctx.commit('addRange', newRange); - - return Promise.resolve(null); - }) - .catch((error) => { - console.error(error); - - throw error; - }) - }, - deleteRange(ctx, calendarRangeId: number) { - const url = `/api/1.0/calendar/calendar-range/${calendarRangeId}.json`; - - makeFetch('DELETE', url) - .then((_) => { - ctx.commit('removeRange', calendarRangeId); - }); - }, - patchRangeTime(ctx, {calendarRangeId, start, end}: {calendarRangeId: number, start: Date, end: Date}): Promise { - const url = `/api/1.0/calendar/calendar-range/${calendarRangeId}.json`; - const body = { - startDate: { - datetime: datetimeToISO(start) + state.key = state.key + 1; }, - endDate: { - datetime: datetimeToISO(end) + }, + actions: { + fetchRanges( + ctx: Context, + payload: { start: Date; end: Date }, + ): Promise { + const start = payload.start; + const end = payload.end; + + if (ctx.rootGetters["me/getMe"] === null) { + return Promise.resolve(ctx.getters.getRangeSource); + } + + if (ctx.getters.isRangeLoaded({ start, end })) { + return Promise.resolve(ctx.getters.getRangeSource); + } + + ctx.commit("addLoaded", { + start: start, + end: end, + }); + + return fetchCalendarRangeForUser( + ctx.rootGetters["me/getMe"], + start, + end, + ).then((ranges: CalendarRange[]) => { + ctx.commit("addRanges", ranges); + return Promise.resolve(null); + }); }, - } as CalendarRangeEdit; + createRange( + ctx, + { + start, + end, + location, + }: { start: Date; end: Date; location: Location }, + ): Promise { + const url = `/api/1.0/calendar/calendar-range.json?`; - return makeFetch('PATCH', url, body) - .then((range) => { - ctx.commit('updateRange', range); - return Promise.resolve(null); - }) - .catch((error) => { - console.error(error); - return Promise.resolve(null); - }) - }, - patchRangeLocation(ctx, {location, calendarRangeId}: {location: Location, calendarRangeId: number}): Promise { - const url = `/api/1.0/calendar/calendar-range/${calendarRangeId}.json`; - const body = { - location: { - id: location.id, - type: "location" + if (ctx.rootState.me.me === null) { + throw new Error("user is currently null"); + } + + const body = { + user: { + id: ctx.rootState.me.me.id, + type: "user", + }, + startDate: { + datetime: datetimeToISO(start), + }, + endDate: { + datetime: datetimeToISO(end), + }, + location: { + id: location.id, + type: "location", + }, + } as CalendarRangeCreate; + + return makeFetch( + "POST", + url, + body, + ) + .then((newRange) => { + ctx.commit("addRange", newRange); + + return Promise.resolve(null); + }) + .catch((error) => { + console.error(error); + + throw error; + }); }, - } as CalendarRangeEdit; + deleteRange(ctx, calendarRangeId: number) { + const url = `/api/1.0/calendar/calendar-range/${calendarRangeId}.json`; - return makeFetch('PATCH', url, body) - .then((range) => { - ctx.commit('updateRange', range); - return Promise.resolve(null); - }) - .catch((error) => { - console.error(error); - return Promise.resolve(null); - }) + makeFetch("DELETE", url).then((_) => { + ctx.commit("removeRange", calendarRangeId); + }); + }, + patchRangeTime( + ctx, + { + calendarRangeId, + start, + end, + }: { calendarRangeId: number; start: Date; end: Date }, + ): Promise { + const url = `/api/1.0/calendar/calendar-range/${calendarRangeId}.json`; + const body = { + startDate: { + datetime: datetimeToISO(start), + }, + endDate: { + datetime: datetimeToISO(end), + }, + } as CalendarRangeEdit; + + return makeFetch( + "PATCH", + url, + body, + ) + .then((range) => { + ctx.commit("updateRange", range); + return Promise.resolve(null); + }) + .catch((error) => { + console.error(error); + return Promise.resolve(null); + }); + }, + patchRangeLocation( + ctx, + { + location, + calendarRangeId, + }: { location: Location; calendarRangeId: number }, + ): Promise { + const url = `/api/1.0/calendar/calendar-range/${calendarRangeId}.json`; + const body = { + location: { + id: location.id, + type: "location", + }, + } as CalendarRangeEdit; + + return makeFetch( + "PATCH", + url, + body, + ) + .then((range) => { + ctx.commit("updateRange", range); + return Promise.resolve(null); + }) + .catch((error) => { + console.error(error); + return Promise.resolve(null); + }); + }, + copyFromDayToAnotherDay( + ctx, + { from, to }: { from: Date; to: Date }, + ): Promise { + const rangesToCopy: EventInputCalendarRange[] = + ctx.getters["getRangesOnDate"](from); + const promises = []; + + for (const r of rangesToCopy) { + const start = new Date(ISOToDatetime(r.start) as Date); + start.setFullYear( + to.getFullYear(), + to.getMonth(), + to.getDate(), + ); + const end = new Date(ISOToDatetime(r.end) as Date); + end.setFullYear(to.getFullYear(), to.getMonth(), to.getDate()); + const location = ctx.rootGetters["locations/getLocationById"]( + r.locationId, + ); + + promises.push( + ctx.dispatch("createRange", { start, end, location }), + ); + } + + return Promise.all(promises).then((_) => Promise.resolve(null)); + }, + copyFromWeekToAnotherWeek( + ctx, + { fromMonday, toMonday }: { fromMonday: Date; toMonday: Date }, + ): Promise { + const rangesToCopy: EventInputCalendarRange[] = + ctx.getters["getRangesOnWeek"](fromMonday); + const promises = []; + const diffTime = toMonday.getTime() - fromMonday.getTime(); + for (const r of rangesToCopy) { + const start = new Date(ISOToDatetime(r.start) as Date); + const end = new Date(ISOToDatetime(r.end) as Date); + start.setTime(start.getTime() + diffTime); + end.setTime(end.getTime() + diffTime); + const location = ctx.rootGetters["locations/getLocationById"]( + r.locationId, + ); + + promises.push( + ctx.dispatch("createRange", { start, end, location }), + ); + } + + return Promise.all(promises).then((_) => Promise.resolve(null)); + }, }, - copyFromDayToAnotherDay(ctx, {from, to}: {from: Date, to: Date}): Promise { - const rangesToCopy: EventInputCalendarRange[] = ctx.getters['getRangesOnDate'](from); - const promises = []; - - for (const r of rangesToCopy) { - const start = new Date((ISOToDatetime(r.start) as Date)); - start.setFullYear(to.getFullYear(), to.getMonth(), to.getDate()); - const end = new Date((ISOToDatetime(r.end) as Date)); - end.setFullYear(to.getFullYear(), to.getMonth(), to.getDate()); - const location = ctx.rootGetters['locations/getLocationById'](r.locationId); - - promises.push(ctx.dispatch('createRange', {start, end, location})); - } - - return Promise.all(promises).then(_ => Promise.resolve(null)); - }, - copyFromWeekToAnotherWeek(ctx, {fromMonday, toMonday}: {fromMonday: Date, toMonday: Date}): Promise { - - const rangesToCopy: EventInputCalendarRange[] = ctx.getters['getRangesOnWeek'](fromMonday); - const promises = []; - const diffTime = toMonday.getTime() - fromMonday.getTime(); - for (const r of rangesToCopy) { - const start = new Date((ISOToDatetime(r.start) as Date)); - const end = new Date((ISOToDatetime(r.end) as Date)); - start.setTime(start.getTime() + diffTime); - end.setTime(end.getTime() + diffTime); - const location = ctx.rootGetters['locations/getLocationById'](r.locationId); - - promises.push(ctx.dispatch('createRange', {start, end, location})); - } - - return Promise.all(promises).then(_ => Promise.resolve(null)); - } - } } as Module; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRemotes.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRemotes.ts index 3fe1e2a34..bd2bf20f8 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRemotes.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/calendarRemotes.ts @@ -1,95 +1,116 @@ -import {State} from './../index'; -import {ActionContext, Module} from 'vuex'; -import {CalendarRemote} from '../../../../types'; -import {fetchCalendarRemoteForUser} from '../../../Calendar/api'; -import {EventInput} from '@fullcalendar/core'; -import {remoteToFullCalendarEvent} from "../../../Calendar/store/utils"; -import {TransportExceptionInterface} from "../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods"; -import {COLORS} from "../../../Calendar/const"; +import { State } from "./../index"; +import { ActionContext, Module } from "vuex"; +import { CalendarRemote } from "../../../../types"; +import { fetchCalendarRemoteForUser } from "../../../Calendar/api"; +import { EventInput } from "@fullcalendar/core"; +import { remoteToFullCalendarEvent } from "../../../Calendar/store/utils"; +import { TransportExceptionInterface } from "../../../../../../../ChillMainBundle/Resources/public/lib/api/apiMethods"; +import { COLORS } from "../../../Calendar/const"; export interface CalendarRemotesState { - remotes: EventInput[], - remotesLoaded: {start: number, end: number}[], - remotesIndex: Set, - key: number + remotes: EventInput[]; + remotesLoaded: { start: number; end: number }[]; + remotesIndex: Set; + key: number; } type Context = ActionContext; export default { - namespaced: true, - state: (): CalendarRemotesState => ({ - remotes: [], - remotesLoaded: [], - remotesIndex: new Set(), - key: 0 - }), - getters: { - isRemotesLoaded: (state: CalendarRemotesState) => ({start, end}: {start: Date, end: Date}): boolean => { - for (const range of state.remotesLoaded) { - if (start.getTime() === range.start && end.getTime() === range.end) { - return true; - } - } + namespaced: true, + state: (): CalendarRemotesState => ({ + remotes: [], + remotesLoaded: [], + remotesIndex: new Set(), + key: 0, + }), + getters: { + isRemotesLoaded: + (state: CalendarRemotesState) => + ({ start, end }: { start: Date; end: Date }): boolean => { + for (const range of state.remotesLoaded) { + if ( + start.getTime() === range.start && + end.getTime() === range.end + ) { + return true; + } + } - return false; + return false; + }, }, - }, - mutations: { - addRemotes(state: CalendarRemotesState, ranges: CalendarRemote[]) { - console.log('addRemotes', ranges); + mutations: { + addRemotes(state: CalendarRemotesState, ranges: CalendarRemote[]) { + console.log("addRemotes", ranges); - const toAdd = ranges - .map(cr => remoteToFullCalendarEvent(cr)) - .filter(r => !state.remotesIndex.has(r.id)); + const toAdd = ranges + .map((cr) => remoteToFullCalendarEvent(cr)) + .filter((r) => !state.remotesIndex.has(r.id)); - toAdd.forEach((r) => { - state.remotesIndex.add(r.id); - state.remotes.push(r); - }); - state.key = state.key + toAdd.length; + toAdd.forEach((r) => { + state.remotesIndex.add(r.id); + state.remotes.push(r); + }); + state.key = state.key + toAdd.length; + }, + addLoaded( + state: CalendarRemotesState, + payload: { start: Date; end: Date }, + ) { + state.remotesLoaded.push({ + start: payload.start.getTime(), + end: payload.end.getTime(), + }); + }, }, - addLoaded(state: CalendarRemotesState, payload: {start: Date, end: Date}) { - state.remotesLoaded.push({start: payload.start.getTime(), end: payload.end.getTime()}); + actions: { + fetchRemotes( + ctx: Context, + payload: { start: Date; end: Date }, + ): Promise { + const start = payload.start; + const end = payload.end; + + if (ctx.rootGetters["me/getMe"] === null) { + return Promise.resolve(null); + } + + if (ctx.getters.isRemotesLoaded({ start, end })) { + return Promise.resolve(ctx.getters.getRangeSource); + } + + ctx.commit("addLoaded", { + start: start, + end: end, + }); + + return fetchCalendarRemoteForUser( + ctx.rootGetters["me/getMe"], + start, + end, + ) + .then((remotes: CalendarRemote[]) => { + // to be add when reactivity problem will be solve ? + //ctx.commit('addRemotes', remotes); + const inputs = remotes + .map((cr) => remoteToFullCalendarEvent(cr)) + .map((cr) => ({ + ...cr, + backgroundColor: COLORS[0], + textColor: "black", + editable: false, + })); + ctx.commit("calendarRanges/addExternals", inputs, { + root: true, + }); + return Promise.resolve(null); + }) + .catch((e: TransportExceptionInterface) => { + console.error(e); + + return Promise.resolve(null); + }); + }, }, - }, - actions: { - fetchRemotes(ctx: Context, payload: {start: Date, end: Date}): Promise { - const start = payload.start; - const end = payload.end; - - if (ctx.rootGetters['me/getMe'] === null) { - return Promise.resolve(null); - } - - if (ctx.getters.isRemotesLoaded({start, end})) { - return Promise.resolve(ctx.getters.getRangeSource); - } - - ctx.commit('addLoaded', { - start: start, - end: end, - }); - - return fetchCalendarRemoteForUser( - ctx.rootGetters['me/getMe'], - start, - end - ) - .then((remotes: CalendarRemote[]) => { - // to be add when reactivity problem will be solve ? - //ctx.commit('addRemotes', remotes); - const inputs = remotes - .map(cr => remoteToFullCalendarEvent(cr)) - .map(cr => ({...cr, backgroundColor: COLORS[0], textColor: 'black', editable: false})) - ctx.commit('calendarRanges/addExternals', inputs, {root: true}); - return Promise.resolve(null); - }) - .catch((e: TransportExceptionInterface) => { - console.error(e); - - return Promise.resolve(null); - }); - } - } } as Module; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/fullcalendar.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/fullcalendar.ts index de379753f..27ef8b8d5 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/fullcalendar.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/fullcalendar.ts @@ -1,56 +1,78 @@ -import {State} from './../index'; -import {ActionContext} from 'vuex'; +import { State } from "./../index"; +import { ActionContext } from "vuex"; export interface FullCalendarState { - currentView: { - start: Date|null, - end: Date|null, - }, - key: number + currentView: { + start: Date | null; + end: Date | null; + }; + key: number; } type Context = ActionContext; export default { - namespaced: true, - state: (): FullCalendarState => ({ - currentView: { - start: null, - end: null, + namespaced: true, + state: (): FullCalendarState => ({ + currentView: { + start: null, + end: null, + }, + key: 0, + }), + mutations: { + setCurrentDatesView: function ( + state: FullCalendarState, + payload: { start: Date; end: Date }, + ): void { + state.currentView.start = payload.start; + state.currentView.end = payload.end; + }, + increaseKey: function (state: FullCalendarState): void { + state.key = state.key + 1; + }, }, - key: 0, - }), - mutations: { - setCurrentDatesView: function(state: FullCalendarState, payload: {start: Date, end: Date}): void { - state.currentView.start = payload.start; - state.currentView.end = payload.end; + actions: { + setCurrentDatesView( + ctx: Context, + { start, end }: { start: Date | null; end: Date | null }, + ): Promise { + console.log("dispatch setCurrentDatesView", { start, end }); + + if ( + ctx.state.currentView.start !== start || + ctx.state.currentView.end !== end + ) { + ctx.commit("setCurrentDatesView", { start, end }); + } + + if (start !== null && end !== null) { + return Promise.all([ + ctx + .dispatch( + "calendarRanges/fetchRanges", + { start, end }, + { root: true }, + ) + .then((_) => Promise.resolve(null)), + ctx + .dispatch( + "calendarRemotes/fetchRemotes", + { start, end }, + { root: true }, + ) + .then((_) => Promise.resolve(null)), + ctx + .dispatch( + "calendarLocals/fetchLocals", + { start, end }, + { root: true }, + ) + .then((_) => Promise.resolve(null)), + ]).then((_) => Promise.resolve(null)); + } else { + return Promise.resolve(null); + } + }, }, - increaseKey: function(state: FullCalendarState): void { - state.key = state.key + 1; - } - }, - actions: { - setCurrentDatesView(ctx: Context, {start, end}: {start: Date|null, end: Date|null}): Promise { - console.log('dispatch setCurrentDatesView', {start, end}); - - if (ctx.state.currentView.start !== start || ctx.state.currentView.end !== end) { - ctx.commit('setCurrentDatesView', {start, end}); - } - - if (start !== null && end !== null) { - - return Promise.all([ - ctx.dispatch('calendarRanges/fetchRanges', {start, end}, {root: true}).then(_ => Promise.resolve(null)), - ctx.dispatch('calendarRemotes/fetchRemotes', {start, end}, {root: true}).then(_ => Promise.resolve(null)), - ctx.dispatch('calendarLocals/fetchLocals', {start, end}, {root: true}).then(_ => Promise.resolve(null)) - ] - ).then(_ => Promise.resolve(null)); - - } else { - return Promise.resolve(null); - } - }, - } -} - - +}; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/location.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/location.ts index 93251e354..91c435810 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/location.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/location.ts @@ -1,62 +1,65 @@ -import {Location} from "../../../../../../../ChillMainBundle/Resources/public/types"; -import {State} from '../index'; -import {Module} from 'vuex'; -import {getLocations} from "../../../../../../../ChillMainBundle/Resources/public/lib/api/locations"; -import {whereami} from "../../../../../../../ChillMainBundle/Resources/public/lib/api/user"; +import { Location } from "../../../../../../../ChillMainBundle/Resources/public/types"; +import { State } from "../index"; +import { Module } from "vuex"; +import { getLocations } from "../../../../../../../ChillMainBundle/Resources/public/lib/api/locations"; +import { whereami } from "../../../../../../../ChillMainBundle/Resources/public/lib/api/user"; export interface LocationState { - locations: Location[]; - locationPicked: Location | null; - currentLocation: Location | null; + locations: Location[]; + locationPicked: Location | null; + currentLocation: Location | null; } export default { - namespaced: true, - state: (): LocationState => { - return { - locations: [], - locationPicked: null, - currentLocation: null, - } - }, - getters: { - getLocationById: (state) => (id: number): Location|undefined => { - return state.locations.find(l => l.id === id); + namespaced: true, + state: (): LocationState => { + return { + locations: [], + locationPicked: null, + currentLocation: null, + }; }, - }, - mutations: { - setLocations(state, locations): void { - state.locations = locations; + getters: { + getLocationById: + (state) => + (id: number): Location | undefined => { + return state.locations.find((l) => l.id === id); + }, }, - setLocationPicked(state, location: Location | null): void { - if (null === location) { - state.locationPicked = null; - return; - } + mutations: { + setLocations(state, locations): void { + state.locations = locations; + }, + setLocationPicked(state, location: Location | null): void { + if (null === location) { + state.locationPicked = null; + return; + } - state.locationPicked = state.locations.find(l => l.id === location.id) || null; - }, - setCurrentLocation(state, location: Location | null): void { - if (null === location) { - state.currentLocation = null; - return; - } + state.locationPicked = + state.locations.find((l) => l.id === location.id) || null; + }, + setCurrentLocation(state, location: Location | null): void { + if (null === location) { + state.currentLocation = null; + return; + } - state.currentLocation = state.locations.find(l => l.id === location.id) || null; - } - }, - actions: { - getLocations(ctx): Promise { - return getLocations().then(locations => { - ctx.commit('setLocations', locations); - return Promise.resolve(); - }); + state.currentLocation = + state.locations.find((l) => l.id === location.id) || null; + }, }, - getCurrentLocation(ctx): Promise { - return whereami().then(location => { - ctx.commit('setCurrentLocation', location); - }) - } - } -} as Module - + actions: { + getLocations(ctx): Promise { + return getLocations().then((locations) => { + ctx.commit("setLocations", locations); + return Promise.resolve(); + }); + }, + getCurrentLocation(ctx): Promise { + return whereami().then((location) => { + ctx.commit("setCurrentLocation", location); + }); + }, + }, +} as Module; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/me.ts b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/me.ts index 8610b76d3..4f83d0185 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/me.ts +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/MyCalendarRange/store/modules/me.ts @@ -1,29 +1,26 @@ -import {State} from './../index'; -import {User} from '../../../../../../../ChillMainBundle/Resources/public/types'; -import {ActionContext} from 'vuex'; +import { State } from "./../index"; +import { User } from "../../../../../../../ChillMainBundle/Resources/public/types"; +import { ActionContext } from "vuex"; export interface MeState { - me: User|null, + me: User | null; } type Context = ActionContext; export default { - namespaced: true, - state: (): MeState => ({ - me: null, - }), - getters: { - getMe: function(state: MeState): User|null { - return state.me; + namespaced: true, + state: (): MeState => ({ + me: null, + }), + getters: { + getMe: function (state: MeState): User | null { + return state.me; + }, }, - }, - mutations: { - setWhoAmi(state: MeState, me: User) { - state.me = me; + mutations: { + setWhoAmi(state: MeState, me: User) { + state.me = me; + }, }, - } }; - - - diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_api/api.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_api/api.js index b2bee8afe..5b54044fe 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_api/api.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_api/api.js @@ -1,103 +1,111 @@ /* -* Endpoint chill_api_single_calendar_range -* method GET, get Calendar ranges -* @returns {Promise} a promise containing all Calendar ranges objects -*/ + * Endpoint chill_api_single_calendar_range + * method GET, get Calendar ranges + * @returns {Promise} a promise containing all Calendar ranges objects + */ const fetchCalendarRanges = () => { return Promise.resolve([]); - const url = `/api/1.0/calendar/calendar-range-available.json`; - return fetch(url) - .then(response => { - if (response.ok) { return response.json(); } - throw Error('Error with request resource response'); - }); + const url = `/api/1.0/calendar/calendar-range-available.json`; + return fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } + throw Error("Error with request resource response"); + }); }; const fetchCalendarRangesByUser = (userId) => { return Promise.resolve([]); - const url = `/api/1.0/calendar/calendar-range-available.json?user=${userId}`; - return fetch(url) - .then(response => { - if (response.ok) { return response.json(); } - throw Error('Error with request resource response'); - }); + const url = `/api/1.0/calendar/calendar-range-available.json?user=${userId}`; + return fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } + throw Error("Error with request resource response"); + }); }; /* -* Endpoint chill_api_single_calendar -* method GET, get Calendar events, can be filtered by mainUser -* @returns {Promise} a promise containing all Calendar objects -*/ + * Endpoint chill_api_single_calendar + * method GET, get Calendar events, can be filtered by mainUser + * @returns {Promise} a promise containing all Calendar objects + */ const fetchCalendar = (mainUserId) => { return Promise.resolve([]); - const url = `/api/1.0/calendar/calendar.json?main_user=${mainUserId}&item_per_page=1000`; - return fetch(url) - .then(response => { - if (response.ok) { return response.json(); } - throw Error('Error with request resource response'); - }); + const url = `/api/1.0/calendar/calendar.json?main_user=${mainUserId}&item_per_page=1000`; + return fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } + throw Error("Error with request resource response"); + }); }; - /* -* Endpoint chill_api_single_calendar_range__entity_create -* method POST, post CalendarRange entity -*/ + * Endpoint chill_api_single_calendar_range__entity_create + * method POST, post CalendarRange entity + */ const postCalendarRange = (body) => { - const url = `/api/1.0/calendar/calendar-range.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 url = `/api/1.0/calendar/calendar-range.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_calendar_range__entity -* method PATCH, patch CalendarRange entity -*/ + * Endpoint chill_api_single_calendar_range__entity + * method PATCH, patch CalendarRange entity + */ const patchCalendarRange = (id, body) => { - console.log(body) - const url = `/api/1.0/calendar/calendar-range/${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'); - }); + console.log(body); + const url = `/api/1.0/calendar/calendar-range/${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"); + }); }; /* -* Endpoint chill_api_single_calendar_range__entity -* method DELETE, delete CalendarRange entity -*/ + * Endpoint chill_api_single_calendar_range__entity + * method DELETE, delete CalendarRange entity + */ const deleteCalendarRange = (id) => { - const url = `/api/1.0/calendar/calendar-range/${id}.json`; - return fetch(url, { - method: 'DELETE', - 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/calendar/calendar-range/${id}.json`; + return fetch(url, { + method: "DELETE", + headers: { + "Content-Type": "application/json;charset=utf-8", + }, + }).then((response) => { + if (response.ok) { + return response.json(); + } + throw Error("Error with request resource response"); + }); }; export { - fetchCalendarRanges, - fetchCalendar, - fetchCalendarRangesByUser, - postCalendarRange, - patchCalendarRange, - deleteCalendarRange + fetchCalendarRanges, + fetchCalendar, + fetchCalendarRangesByUser, + postCalendarRange, + patchCalendarRange, + deleteCalendarRange, }; diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/CalendarUserSelector.vue b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/CalendarUserSelector.vue index 6ed65791b..97d4c6f53 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/CalendarUserSelector.vue +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/CalendarUserSelector.vue @@ -1,223 +1,259 @@ - diff --git a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/js/i18n.js b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/js/i18n.js index 2f7d15662..38e06c15c 100644 --- a/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/js/i18n.js +++ b/src/Bundle/ChillCalendarBundle/Resources/public/vuejs/_components/CalendarUserSelector/js/i18n.js @@ -1,17 +1,14 @@ -import { multiSelectMessages } from 'ChillMainAssets/vuejs/_js/i18n' +import { multiSelectMessages } from "ChillMainAssets/vuejs/_js/i18n"; const calendarUserSelectorMessages = { fr: { choose_your_calendar_user: "Afficher les plages de disponibilités", select_user: "Sélectionnez des calendriers", show_my_calendar: "Afficher mon calendrier", - show_weekends: "Afficher les week-ends" - } + show_weekends: "Afficher les week-ends", + }, }; - + Object.assign(calendarUserSelectorMessages.fr, multiSelectMessages.fr); -export { - calendarUserSelectorMessages -}; - \ No newline at end of file +export { calendarUserSelectorMessages }; diff --git a/src/Bundle/ChillCalendarBundle/chill.webpack.config.js b/src/Bundle/ChillCalendarBundle/chill.webpack.config.js index 9d45a3142..50db64135 100644 --- a/src/Bundle/ChillCalendarBundle/chill.webpack.config.js +++ b/src/Bundle/ChillCalendarBundle/chill.webpack.config.js @@ -1,14 +1,25 @@ // this file loads all assets from the Chill calendar bundle -module.exports = function(encore, entries) { +module.exports = function (encore, entries) { + entries.push(__dirname + "/Resources/public/chill/chill.js"); - entries.push(__dirname + '/Resources/public/chill/chill.js'); + encore.addAliases({ + ChillCalendarAssets: __dirname + "/Resources/public", + }); - encore.addAliases({ - ChillCalendarAssets: __dirname + '/Resources/public' - }); - - encore.addEntry('vue_calendar', __dirname + '/Resources/public/vuejs/Calendar/index.js'); - encore.addEntry('vue_mycalendarrange', __dirname + '/Resources/public/vuejs/MyCalendarRange/index2.ts'); - encore.addEntry('page_calendar', __dirname + '/Resources/public/chill/index.js'); - encore.addEntry('mod_answer', __dirname + '/Resources/public/module/Invite/answer.js'); + encore.addEntry( + "vue_calendar", + __dirname + "/Resources/public/vuejs/Calendar/index.js", + ); + encore.addEntry( + "vue_mycalendarrange", + __dirname + "/Resources/public/vuejs/MyCalendarRange/index2.ts", + ); + encore.addEntry( + "page_calendar", + __dirname + "/Resources/public/chill/index.js", + ); + encore.addEntry( + "mod_answer", + __dirname + "/Resources/public/module/Invite/answer.js", + ); }; diff --git a/src/Bundle/ChillDocGeneratorBundle/Resources/public/api/pickTemplate.js b/src/Bundle/ChillDocGeneratorBundle/Resources/public/api/pickTemplate.js index 4c5673d05..9b0b61d16 100644 --- a/src/Bundle/ChillDocGeneratorBundle/Resources/public/api/pickTemplate.js +++ b/src/Bundle/ChillDocGeneratorBundle/Resources/public/api/pickTemplate.js @@ -1,10 +1,8 @@ import { fetchResults } from "ChillMainAssets/lib/api/apiMethods.ts"; const fetchTemplates = (entityClass) => { - let fqdnEntityClass = encodeURI(entityClass); - return fetchResults(`/api/1.0/docgen/templates/by-entity/${fqdnEntityClass}`); -} - -export { - fetchTemplates + let fqdnEntityClass = encodeURI(entityClass); + return fetchResults(`/api/1.0/docgen/templates/by-entity/${fqdnEntityClass}`); }; + +export { fetchTemplates }; diff --git a/src/Bundle/ChillDocGeneratorBundle/Resources/public/lib/document-generator.js b/src/Bundle/ChillDocGeneratorBundle/Resources/public/lib/document-generator.js index beea190a3..3d480ae8f 100644 --- a/src/Bundle/ChillDocGeneratorBundle/Resources/public/lib/document-generator.js +++ b/src/Bundle/ChillDocGeneratorBundle/Resources/public/lib/document-generator.js @@ -1,13 +1,12 @@ - -const buildLink = function(templateId, entityId, entityClass) { - const - entityIdEncoded = encodeURI(entityId), - returnPath = encodeURIComponent(window.location.pathname + window.location.search + window.location.hash), - entityClassEncoded = encodeURI(entityClass), - url = `/fr/doc/gen/generate/from/${templateId}/for/${entityClassEncoded}/${entityIdEncoded}?returnPath=${returnPath}` - ; - console.log('computed Url'); - return url; +const buildLink = function (templateId, entityId, entityClass) { + const entityIdEncoded = encodeURI(entityId), + returnPath = encodeURIComponent( + window.location.pathname + window.location.search + window.location.hash, + ), + entityClassEncoded = encodeURI(entityClass), + url = `/fr/doc/gen/generate/from/${templateId}/for/${entityClassEncoded}/${entityIdEncoded}?returnPath=${returnPath}`; + console.log("computed Url"); + return url; }; -export {buildLink}; +export { buildLink }; diff --git a/src/Bundle/ChillDocGeneratorBundle/Resources/public/module/PickTemplate/index.js b/src/Bundle/ChillDocGeneratorBundle/Resources/public/module/PickTemplate/index.js index 9d26d1009..ff8fd7193 100644 --- a/src/Bundle/ChillDocGeneratorBundle/Resources/public/module/PickTemplate/index.js +++ b/src/Bundle/ChillDocGeneratorBundle/Resources/public/module/PickTemplate/index.js @@ -1,27 +1,25 @@ -import {createApp} from 'vue'; -import PickTemplate from 'ChillDocGeneratorAssets/vuejs/_components/PickTemplate.vue'; -import {fetchTemplates} from 'ChillDocGeneratorAssets/api/pickTemplate.js'; -import {_createI18n} from 'ChillMainAssets/vuejs/_js/i18n'; +import { createApp } from "vue"; +import PickTemplate from "ChillDocGeneratorAssets/vuejs/_components/PickTemplate.vue"; +import { fetchTemplates } from "ChillDocGeneratorAssets/api/pickTemplate.js"; +import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n"; const i18n = _createI18n({}); -document.querySelectorAll('div[data-docgen-template-picker]').forEach(el => { - fetchTemplates(el.dataset.entityClass).then(templates => { - let - picker = { - template: '', - components: { - PickTemplate, - }, - data() { - return { - templates: templates, - entityId: el.dataset.entityId, - } - }, - } - ; - createApp(picker).use(i18n).mount(el); - }) - +document.querySelectorAll("div[data-docgen-template-picker]").forEach((el) => { + fetchTemplates(el.dataset.entityClass).then((templates) => { + let picker = { + template: + '', + components: { + PickTemplate, + }, + data() { + return { + templates: templates, + entityId: el.dataset.entityId, + }; + }, + }; + createApp(picker).use(i18n).mount(el); + }); }); diff --git a/src/Bundle/ChillDocGeneratorBundle/Resources/public/vuejs/_components/PickTemplate.vue b/src/Bundle/ChillDocGeneratorBundle/Resources/public/vuejs/_components/PickTemplate.vue index 4094de5a4..a8b48404c 100644 --- a/src/Bundle/ChillDocGeneratorBundle/Resources/public/vuejs/_components/PickTemplate.vue +++ b/src/Bundle/ChillDocGeneratorBundle/Resources/public/vuejs/_components/PickTemplate.vue @@ -1,70 +1,60 @@ - + diff --git a/src/Bundle/ChillDocGeneratorBundle/chill.webpack.config.js b/src/Bundle/ChillDocGeneratorBundle/chill.webpack.config.js index 9017c7e08..f97e33019 100644 --- a/src/Bundle/ChillDocGeneratorBundle/chill.webpack.config.js +++ b/src/Bundle/ChillDocGeneratorBundle/chill.webpack.config.js @@ -1,8 +1,11 @@ // this file loads all assets from the Chill DocGenerator bundle -module.exports = function(encore, entries) { - encore.addAliases({ - ChillDocGeneratorAssets: __dirname + '/Resources/public' - }); +module.exports = function (encore, entries) { + encore.addAliases({ + ChillDocGeneratorAssets: __dirname + "/Resources/public", + }); - encore.addEntry('mod_docgen_picktemplate', __dirname + '/Resources/public/module/PickTemplate/index.js'); + encore.addEntry( + "mod_docgen_picktemplate", + __dirname + "/Resources/public/module/PickTemplate/index.js", + ); }; diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/downloader.js b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/downloader.js index 2b6a1b8ae..9f0cfe1a6 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/downloader.js +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/downloader.js @@ -1,96 +1,99 @@ -var mime = require('mime'); +var mime = require("mime"); -var algo = 'AES-CBC'; +var algo = "AES-CBC"; var initializeButtons = (root) => { - var - buttons = root.querySelectorAll('a[data-download-button]'); + var buttons = root.querySelectorAll("a[data-download-button]"); - for (let i = 0; i < buttons.length; i ++) { - initialize(buttons[i]); - } + for (let i = 0; i < buttons.length; i++) { + initialize(buttons[i]); + } }; var initialize = (button) => { - button.addEventListener('click', onClick); + button.addEventListener("click", onClick); }; -var onClick = e => download(e.target); +var onClick = (e) => download(e.target); var download = (button) => { - var - keyData = JSON.parse(button.dataset.key), - ivData = JSON.parse(button.dataset.iv), - iv = new Uint8Array(ivData), - urlGenerator = button.dataset.tempUrlGetGenerator, - hasFilename = 'filename' in button.dataset, - filename = button.dataset.filename, - labelPreparing = button.dataset.labelPreparing, - labelReady = button.dataset.labelReady, - mimeType = button.dataset.mimeType, - extension = mime.getExtension(mimeType), - decryptError = "Error while decrypting file", - fetchError = "Error while fetching file", - key, url - ; + var keyData = JSON.parse(button.dataset.key), + ivData = JSON.parse(button.dataset.iv), + iv = new Uint8Array(ivData), + urlGenerator = button.dataset.tempUrlGetGenerator, + hasFilename = "filename" in button.dataset, + filename = button.dataset.filename, + labelPreparing = button.dataset.labelPreparing, + labelReady = button.dataset.labelReady, + mimeType = button.dataset.mimeType, + extension = mime.getExtension(mimeType), + decryptError = "Error while decrypting file", + fetchError = "Error while fetching file", + key, + url; - button.textContent = labelPreparing; + button.textContent = labelPreparing; - window.fetch(urlGenerator) - .then((r) => { - if (r.ok) { - return r.json(); - } else { - throw new Error("error while downloading url " + r.status + " " + r.statusText); - } - }) - .then(data => { - return window.fetch(data.url); - }) - .then(response => { - if (response.ok) { - return response.arrayBuffer(); - } - throw new Error(response.status + response.statusText); - }) - .then(buffer => { - if (keyData.alg !== undefined) { - return window.crypto.subtle - .importKey('jwk', keyData, { name: algo, iv: iv}, false, ['decrypt']) - .then(key => { - return window.crypto.subtle.decrypt({ name: algo, iv: iv }, key, buffer); - }); - } - return Promise.resolve(buffer); - }) - .then(decrypted => { - var - blob = new Blob([decrypted], { type: mimeType }), - url = window.URL.createObjectURL(blob) - ; - button.href = url; - button.target = '_blank'; - button.type = mimeType; - button.textContent = labelReady; - if (hasFilename) { - - button.download = filename; - if (extension !== false) { - button.download = button.download + '.' + extension; - } - } - button.removeEventListener('click', onClick); - button.click(); - }) - .catch(error => { - button.textContent = ""; - button.appendChild(document.createTextNode("error while handling decrypted file")); - }) - ; + window + .fetch(urlGenerator) + .then((r) => { + if (r.ok) { + return r.json(); + } else { + throw new Error( + "error while downloading url " + r.status + " " + r.statusText, + ); + } + }) + .then((data) => { + return window.fetch(data.url); + }) + .then((response) => { + if (response.ok) { + return response.arrayBuffer(); + } + throw new Error(response.status + response.statusText); + }) + .then((buffer) => { + if (keyData.alg !== undefined) { + return window.crypto.subtle + .importKey("jwk", keyData, { name: algo, iv: iv }, false, ["decrypt"]) + .then((key) => { + return window.crypto.subtle.decrypt( + { name: algo, iv: iv }, + key, + buffer, + ); + }); + } + return Promise.resolve(buffer); + }) + .then((decrypted) => { + var blob = new Blob([decrypted], { type: mimeType }), + url = window.URL.createObjectURL(blob); + button.href = url; + button.target = "_blank"; + button.type = mimeType; + button.textContent = labelReady; + if (hasFilename) { + button.download = filename; + if (extension !== false) { + button.download = button.download + "." + extension; + } + } + button.removeEventListener("click", onClick); + button.click(); + }) + .catch((error) => { + button.textContent = ""; + button.appendChild( + document.createTextNode("error while handling decrypted file"), + ); + }); }; -window.addEventListener('load', function(e) { - initializeButtons(e.target); +window.addEventListener("load", function (e) { + initializeButtons(e.target); }); export { initializeButtons, download }; diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index-old.js b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index-old.js index 9fa7deeeb..e89a18869 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index-old.js +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index-old.js @@ -1,2 +1,2 @@ -require('./uploader.js'); -require('./downloader.js'); \ No newline at end of file +require("./uploader.js"); +require("./downloader.js"); diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index.ts b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index.ts index ee731606f..831119a22 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index.ts +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/index.ts @@ -1,18 +1,22 @@ -import {CollectionEventPayload} from "../../../../../ChillMainBundle/Resources/public/module/collection"; -import {createApp} from "vue"; -import DropFileWidget from "../../vuejs/DropFileWidget/DropFileWidget.vue" -import {StoredObject, StoredObjectCreated} from "../../types"; -import {_createI18n} from "../../../../../ChillMainBundle/Resources/public/vuejs/_js/i18n"; +import { CollectionEventPayload } from "../../../../../ChillMainBundle/Resources/public/module/collection"; +import { createApp } from "vue"; +import DropFileWidget from "../../vuejs/DropFileWidget/DropFileWidget.vue"; +import { StoredObject, StoredObjectCreated } from "../../types"; +import { _createI18n } from "../../../../../ChillMainBundle/Resources/public/vuejs/_js/i18n"; const i18n = _createI18n({}); -const startApp = (divElement: HTMLDivElement, collectionEntry: null|HTMLLIElement): void => { - console.log('app started', divElement); - const input_stored_object: HTMLInputElement|null = divElement.querySelector("input[data-stored-object]"); +const startApp = ( + divElement: HTMLDivElement, + collectionEntry: null | HTMLLIElement, +): void => { + console.log("app started", divElement); + const input_stored_object: HTMLInputElement | null = + divElement.querySelector("input[data-stored-object]"); if (null === input_stored_object) { - throw new Error('input to stored object not found'); + throw new Error("input to stored object not found"); } - let existingDoc: StoredObject|null = null; + let existingDoc: StoredObject | null = null; if (input_stored_object.value !== "") { existingDoc = JSON.parse(input_stored_object.value); } @@ -20,67 +24,77 @@ const startApp = (divElement: HTMLDivElement, collectionEntry: null|HTMLLIElemen divElement.appendChild(app_container); const app = createApp({ - template: '', + template: + '', data(vm) { return { existingDoc: existingDoc, - } + }; }, components: { DropFileWidget, }, methods: { - addDocument: function(object: StoredObjectCreated): void { - console.log('object added', object); + addDocument: function (object: StoredObjectCreated): void { + console.log("object added", object); this.$data.existingDoc = object; input_stored_object.value = JSON.stringify(object); }, - removeDocument: function(object: StoredObject): void { - console.log('catch remove document', object); + removeDocument: function (object: StoredObject): void { + console.log("catch remove document", object); input_stored_object.value = ""; this.$data.existingDoc = null; - console.log('collectionEntry', collectionEntry); + console.log("collectionEntry", collectionEntry); if (null !== collectionEntry) { - console.log('will remove collection'); + console.log("will remove collection"); collectionEntry.remove(); } - } - } + }, + }, }); app.use(i18n).mount(app_container); -} -window.addEventListener('collection-add-entry', ((e: CustomEvent) => { +}; +window.addEventListener("collection-add-entry", (( + e: CustomEvent, +) => { const detail = e.detail; - const divElement: null|HTMLDivElement = detail.entry.querySelector('div[data-stored-object]'); + const divElement: null | HTMLDivElement = detail.entry.querySelector( + "div[data-stored-object]", + ); if (null === divElement) { - throw new Error('div[data-stored-object] not found'); + throw new Error("div[data-stored-object] not found"); } startApp(divElement, detail.entry); }) as EventListener); -window.addEventListener('DOMContentLoaded', () => { - const upload_inputs: NodeListOf = document.querySelectorAll('div[data-stored-object]'); +window.addEventListener("DOMContentLoaded", () => { + const upload_inputs: NodeListOf = document.querySelectorAll( + "div[data-stored-object]", + ); upload_inputs.forEach((input: HTMLDivElement): void => { // test for a parent to check if this is a collection entry - let collectionEntry: null|HTMLLIElement = null; + let collectionEntry: null | HTMLLIElement = null; const parent = input.parentElement; - console.log('parent', parent); + console.log("parent", parent); if (null !== parent) { const grandParent = parent.parentElement; - console.log('grandParent', grandParent); + console.log("grandParent", grandParent); if (null !== grandParent) { - if (grandParent.tagName.toLowerCase() === 'li' && grandParent.classList.contains('entry')) { + if ( + grandParent.tagName.toLowerCase() === "li" && + grandParent.classList.contains("entry") + ) { collectionEntry = grandParent as HTMLLIElement; } } } startApp(input, collectionEntry); - }) + }); }); -export {} +export {}; diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/uploader.js b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/uploader.js index 5def6a0b2..12201e9f2 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/uploader.js +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/module/async_upload/uploader.js @@ -1,7 +1,6 @@ -var algo = 'AES-CBC'; -import Dropzone from 'dropzone'; -import { initializeButtons } from './downloader.js'; - +var algo = "AES-CBC"; +import Dropzone from "dropzone"; +import { initializeButtons } from "./downloader.js"; /** * @@ -23,351 +22,335 @@ import { initializeButtons } from './downloader.js'; // load css //require('dropzone/dist/basic.css'); -require('dropzone/dist/dropzone.css'); -require('./index.scss'); +require("dropzone/dist/dropzone.css"); +require("./index.scss"); // // disable dropzone autodiscover Dropzone.autoDiscover = false; var keyDefinition = { - name: algo, - length: 256 + name: algo, + length: 256, }; -var searchForZones = function(root) { - var zones = root.querySelectorAll('div[data-stored-object]'); - for(let i=0; i < zones.length; i++) { - initialize(zones[i]); - } +var searchForZones = function (root) { + var zones = root.querySelectorAll("div[data-stored-object]"); + for (let i = 0; i < zones.length; i++) { + initialize(zones[i]); + } }; -var getUploadUrl = function(zoneData, files) { - var - generateTempUrlPost = zoneData.zone.querySelector('input[data-async-file-upload]').dataset.generateTempUrlPost, - oReq = new XMLHttpRequest() - ; +var getUploadUrl = function (zoneData, files) { + var generateTempUrlPost = zoneData.zone.querySelector( + "input[data-async-file-upload]", + ).dataset.generateTempUrlPost, + oReq = new XMLHttpRequest(); + // arg, dropzone, you cannot handle async upload... + oReq.open("GET", generateTempUrlPost, false); + oReq.send(); - // arg, dropzone, you cannot handle async upload... - oReq.open("GET", generateTempUrlPost, false); - oReq.send(); + if (oReq.readyState !== XMLHttpRequest.DONE) { + throw new Error("Error while fetching url to upload"); + } - if (oReq.readyState !== XMLHttpRequest.DONE) { - throw new Error("Error while fetching url to upload"); - } + zoneData.params = JSON.parse(oReq.responseText); - zoneData.params = JSON.parse(oReq.responseText); - - return zoneData.params.url; + return zoneData.params.url; }; -var encryptFile = function(originalFile, zoneData, done) { - var - iv = crypto.getRandomValues(new Uint8Array(16)), - reader = new FileReader(), - jsKey, rawKey - ; +var encryptFile = function (originalFile, zoneData, done) { + var iv = crypto.getRandomValues(new Uint8Array(16)), + reader = new FileReader(), + jsKey, + rawKey; - zoneData.originalType = originalFile.type; + zoneData.originalType = originalFile.type; - reader.onload = e => { - window.crypto.subtle.generateKey(keyDefinition, true, [ "encrypt", "decrypt" ]) - .then(key => { - jsKey = key; + reader.onload = (e) => { + window.crypto.subtle + .generateKey(keyDefinition, true, ["encrypt", "decrypt"]) + .then((key) => { + jsKey = key; - // we register the key somwhere - return window.crypto.subtle.exportKey('jwk', key); - }).then(exportedKey => { - rawKey = exportedKey; + // we register the key somwhere + return window.crypto.subtle.exportKey("jwk", key); + }) + .then((exportedKey) => { + rawKey = exportedKey; - // we start encryption - return window.crypto.subtle.encrypt({ name: algo, iv: iv}, jsKey, e.target.result); - }) - .then(encrypted => { - zoneData.crypto = { - jsKey: jsKey, - rawKey: rawKey, - iv: iv - }; + // we start encryption + return window.crypto.subtle.encrypt( + { name: algo, iv: iv }, + jsKey, + e.target.result, + ); + }) + .then((encrypted) => { + zoneData.crypto = { + jsKey: jsKey, + rawKey: rawKey, + iv: iv, + }; - done(new File( [ encrypted ], zoneData.suffix)); - }); - }; + done(new File([encrypted], zoneData.suffix)); + }); + }; - reader.readAsArrayBuffer(originalFile); + reader.readAsArrayBuffer(originalFile); }; var addBelowButton = (btn, zone, zoneData) => { - let - belowZone = zone.querySelector('.chill-dropzone__below-zone'); + let belowZone = zone.querySelector(".chill-dropzone__below-zone"); - if (belowZone === null) { - belowZone = document.createElement('div'); - belowZone.classList.add('chill-dropzone__below-zone'); - zone.appendChild(belowZone); - } + if (belowZone === null) { + belowZone = document.createElement("div"); + belowZone.classList.add("chill-dropzone__below-zone"); + zone.appendChild(belowZone); + } - belowZone.appendChild(btn); + belowZone.appendChild(btn); }; var createZone = (zone, zoneData) => { - var - created = document.createElement('div'), - initMessage = document.createElement('div'), - initContent = zone.dataset.labelInitMessage, - dropzoneI; + var created = document.createElement("div"), + initMessage = document.createElement("div"), + initContent = zone.dataset.labelInitMessage, + dropzoneI; - created.classList.add('dropzone'); - initMessage.classList.add('dz-message'); - initMessage.appendChild(document.createTextNode(initContent)); - console.log(Dropzone); - dropzoneI = new Dropzone(created, { - url: function(files) { - return getUploadUrl(zoneData, files); - }, - dictDefaultMessage: zone.dataset.dictDefaultMessage, - dictFileTooBig: zone.dataset.dictFileTooBig, - dictRemoveFile: zone.dataset.dictRemoveFile, - dictMaxFilesExceeded: zone.dataset.dictMaxFilesExceeded, - dictCancelUpload: zone.dataset.dictCancelUpload, - dictCancelUploadConfirm: zone.dataset.dictCancelUploadConfirm, - dictUploadCanceled: zone.dataset.dictUploadCanceled, - maxFiles: 1, - addRemoveLinks: true, - transformFile: function(file, done) { - encryptFile(file, zoneData, done); - }, - renameFile: function(file) { - return zoneData.suffix; - } - }); + created.classList.add("dropzone"); + initMessage.classList.add("dz-message"); + initMessage.appendChild(document.createTextNode(initContent)); + console.log(Dropzone); + dropzoneI = new Dropzone(created, { + url: function (files) { + return getUploadUrl(zoneData, files); + }, + dictDefaultMessage: zone.dataset.dictDefaultMessage, + dictFileTooBig: zone.dataset.dictFileTooBig, + dictRemoveFile: zone.dataset.dictRemoveFile, + dictMaxFilesExceeded: zone.dataset.dictMaxFilesExceeded, + dictCancelUpload: zone.dataset.dictCancelUpload, + dictCancelUploadConfirm: zone.dataset.dictCancelUploadConfirm, + dictUploadCanceled: zone.dataset.dictUploadCanceled, + maxFiles: 1, + addRemoveLinks: true, + transformFile: function (file, done) { + encryptFile(file, zoneData, done); + }, + renameFile: function (file) { + return zoneData.suffix; + }, + }); - dropzoneI.on("sending", function(file, xhr, formData) { - formData.append("redirect", zoneData.params.redirect); - formData.append("max_file_size", zoneData.params.max_file_size); - formData.append("max_file_count", zoneData.params.max_file_count); - formData.append("expires", zoneData.params.expires); - formData.append("signature", zoneData.params.signature); - }); + dropzoneI.on("sending", function (file, xhr, formData) { + formData.append("redirect", zoneData.params.redirect); + formData.append("max_file_size", zoneData.params.max_file_size); + formData.append("max_file_count", zoneData.params.max_file_count); + formData.append("expires", zoneData.params.expires); + formData.append("signature", zoneData.params.signature); + }); - dropzoneI.on("success", function(file, response) { - zoneData.currentFile = file; - storeDataInForm(zone, zoneData); - }); + dropzoneI.on("success", function (file, response) { + zoneData.currentFile = file; + storeDataInForm(zone, zoneData); + }); - dropzoneI.on("addedfile", function(file) { - if (zoneData.hasOwnProperty('currentFile')) { - dropzoneI.removeFile(zoneData.currentFile); - } - }); + dropzoneI.on("addedfile", function (file) { + if (zoneData.hasOwnProperty("currentFile")) { + dropzoneI.removeFile(zoneData.currentFile); + } + }); - dropzoneI.on("removedfile", function(file) { - removeDataInForm(zone, zoneData); - }); + dropzoneI.on("removedfile", function (file) { + removeDataInForm(zone, zoneData); + }); - zone.insertBefore(created, zone.firstChild); + zone.insertBefore(created, zone.firstChild); - let event = new CustomEvent("chill_dropzone_initialized", { - detail: { - dropzone: dropzoneI, - zoneData: zoneData - } - }); - window.dispatchEvent(event); + let event = new CustomEvent("chill_dropzone_initialized", { + detail: { + dropzone: dropzoneI, + zoneData: zoneData, + }, + }); + window.dispatchEvent(event); }; - -var initialize = function(zone) { - var - allowRemove = zone.dataset.allowRemove, - zoneData = { zone: zone, suffix: createFilename(), allowRemove: allowRemove, old: null } - ; - - if (hasDataInForm(zone, zoneData)) { - insertRemoveButton(zone, zoneData); - insertDownloadButton(zone, zoneData); - } else { - createZone(zone, zoneData); - } +var initialize = function (zone) { + var allowRemove = zone.dataset.allowRemove, + zoneData = { + zone: zone, + suffix: createFilename(), + allowRemove: allowRemove, + old: null, + }; + if (hasDataInForm(zone, zoneData)) { + insertRemoveButton(zone, zoneData); + insertDownloadButton(zone, zoneData); + } else { + createZone(zone, zoneData); + } }; var createFilename = () => { - var text = ""; - var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + var text = ""; + var possible = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - for (let i = 0; i < 7; i++) { - text += possible.charAt(Math.floor(Math.random() * possible.length)); - } + for (let i = 0; i < 7; i++) { + text += possible.charAt(Math.floor(Math.random() * possible.length)); + } - return text; + return text; }; var storeDataInForm = (zone, zoneData) => { - var - inputKey = zone.querySelector('input[data-stored-object-key]'), - inputIv = zone.querySelector('input[data-stored-object-iv]'), - inputObject = zone.querySelector('input[data-async-file-upload]'), - inputType = zone.querySelector('input[data-async-file-type]') - ; + var inputKey = zone.querySelector("input[data-stored-object-key]"), + inputIv = zone.querySelector("input[data-stored-object-iv]"), + inputObject = zone.querySelector("input[data-async-file-upload]"), + inputType = zone.querySelector("input[data-async-file-type]"); + inputKey.value = JSON.stringify(zoneData.crypto.rawKey); + inputIv.value = JSON.stringify(Array.from(zoneData.crypto.iv)); + inputType.value = zoneData.originalType; + inputObject.value = zoneData.params.prefix + zoneData.suffix; - inputKey.value = JSON.stringify(zoneData.crypto.rawKey); - inputIv.value = JSON.stringify(Array.from(zoneData.crypto.iv)); - inputType.value = zoneData.originalType; - inputObject.value = zoneData.params.prefix + zoneData.suffix; - - insertDownloadButton(zone); + insertDownloadButton(zone); }; const restoreDataInForm = (zone, zoneData) => { - var - inputKey = zone.querySelector('input[data-stored-object-key]'), - inputIv = zone.querySelector('input[data-stored-object-iv]'), - inputObject = zone.querySelector('input[data-async-file-upload]'), - inputType = zone.querySelector('input[data-async-file-type]') - ; + var inputKey = zone.querySelector("input[data-stored-object-key]"), + inputIv = zone.querySelector("input[data-stored-object-iv]"), + inputObject = zone.querySelector("input[data-async-file-upload]"), + inputType = zone.querySelector("input[data-async-file-type]"); + if (zoneData.old === null) { + console.log("should not have restored data"); + return; + } - if (zoneData.old === null) { - console.log('should not have restored data'); - return; - } + inputKey.value = zoneData.old.key; + inputIv.value = zoneData.old.iv; + inputType.value = zoneData.old.type; + inputObject.value = zoneData.old.obj; - inputKey.value = zoneData.old.key; - inputIv.value = zoneData.old.iv; - inputType.value = zoneData.old.type; - inputObject.value = zoneData.old.obj; - - insertDownloadButton(zone); + insertDownloadButton(zone); }; const hasDataInForm = (zone, zoneData) => { - var - inputObject = zone.querySelector('input[data-async-file-upload]') - ; - - return inputObject.value.length > 0; + var inputObject = zone.querySelector("input[data-async-file-upload]"); + return inputObject.value.length > 0; }; var removeDataInForm = (zone, zoneData) => { - var - inputKey = zone.querySelector('input[data-stored-object-key]'), - inputIv = zone.querySelector('input[data-stored-object-iv]'), - inputObject = zone.querySelector('input[data-async-file-upload]'), - inputType = zone.querySelector('input[data-async-file-type]') - ; + var inputKey = zone.querySelector("input[data-stored-object-key]"), + inputIv = zone.querySelector("input[data-stored-object-iv]"), + inputObject = zone.querySelector("input[data-async-file-upload]"), + inputType = zone.querySelector("input[data-async-file-type]"); + // store data for future usage + zoneData.old = { + key: inputKey.value, + iv: inputIv.value, + obj: inputObject.value, + type: inputType.value, + }; + // set blank values + inputKey.value = ""; + inputIv.value = ""; + inputType.value = ""; + inputObject.value = ""; - // store data for future usage - zoneData.old = { - key: inputKey.value, - iv: inputIv.value, - obj: inputObject.value, - type: inputType.value - }; - // set blank values - inputKey.value = ""; - inputIv.value = ""; - inputType.value = ""; - inputObject.value = ""; - - insertDownloadButton(zone); + insertDownloadButton(zone); }; var insertRemoveButton = (zone, zoneData) => { - var - removeButton = document.createElement('a'), - cancelButton = document.createElement('a'), - labelRemove = zone.dataset.dictRemove, - labelCancel = 'Restaurer' - ; + var removeButton = document.createElement("a"), + cancelButton = document.createElement("a"), + labelRemove = zone.dataset.dictRemove, + labelCancel = "Restaurer"; + removeButton.classList.add("btn", "btn-delete"); + removeButton.textContent = labelRemove; - removeButton.classList.add('btn', 'btn-delete'); - removeButton.textContent = labelRemove; + cancelButton.classList.add("btn", "btn-cancel"); + cancelButton.textContent = labelCancel; - cancelButton.classList.add('btn', 'btn-cancel'); - cancelButton.textContent = labelCancel; - - removeButton.addEventListener('click', (e) => { + removeButton.addEventListener("click", (e) => { + e.preventDefault(); + if (zoneData.allowRemove === "true") { + removeDataInForm(zone, zoneData); + cancelButton.addEventListener("click", (e) => { e.preventDefault(); - if (zoneData.allowRemove === 'true') { - removeDataInForm(zone, zoneData); - cancelButton.addEventListener('click', (e) => { - e.preventDefault(); - restoreDataInForm(zone, zoneData); + restoreDataInForm(zone, zoneData); - cancelButton.remove(); - zone.querySelector('.dropzone').remove(); + cancelButton.remove(); + zone.querySelector(".dropzone").remove(); - initialize(zone); - }); - } - addBelowButton(cancelButton, zone, zoneData); - //zone.appendChild(cancelButton); - removeButton.remove(); - createZone(zone, zoneData); - }); + initialize(zone); + }); + } + addBelowButton(cancelButton, zone, zoneData); + //zone.appendChild(cancelButton); + removeButton.remove(); + createZone(zone, zoneData); + }); - addBelowButton(removeButton, zone, zoneData); - // zone.appendChild(removeButton); + addBelowButton(removeButton, zone, zoneData); + // zone.appendChild(removeButton); }; const removeDownloadButton = (zone, zoneData) => { - var - existingButtons = zone.querySelectorAll('a[data-download-button]') - ; - - // remove existing - existingButtons.forEach(function(b) { - b.remove(); - }); + var existingButtons = zone.querySelectorAll("a[data-download-button]"); + // remove existing + existingButtons.forEach(function (b) { + b.remove(); + }); }; var insertDownloadButton = (zone, zoneData) => { - var - existingButtons = zone.querySelectorAll('a[data-download-button]'), - newButton = document.createElement('a'), - inputKey = zone.querySelector('input[data-stored-object-key]'), - inputIv = zone.querySelector('input[data-stored-object-iv]'), - inputObject = zone.querySelector('input[data-async-file-upload]'), - inputType = zone.querySelector('input[data-async-file-type]'), - labelPreparing = zone.dataset.labelPreparing, - labelQuietButton = zone.dataset.labelQuietButton, - labelReady = zone.dataset.labelReady, - tempUrlGenerator = zone.dataset.tempUrlGenerator, - tempUrlGeneratorParams = new URLSearchParams() - ; + var existingButtons = zone.querySelectorAll("a[data-download-button]"), + newButton = document.createElement("a"), + inputKey = zone.querySelector("input[data-stored-object-key]"), + inputIv = zone.querySelector("input[data-stored-object-iv]"), + inputObject = zone.querySelector("input[data-async-file-upload]"), + inputType = zone.querySelector("input[data-async-file-type]"), + labelPreparing = zone.dataset.labelPreparing, + labelQuietButton = zone.dataset.labelQuietButton, + labelReady = zone.dataset.labelReady, + tempUrlGenerator = zone.dataset.tempUrlGenerator, + tempUrlGeneratorParams = new URLSearchParams(); + // remove existing + existingButtons.forEach(function (b) { + b.remove(); + }); - // remove existing - existingButtons.forEach(function(b) { - b.remove(); - }); + if (inputObject.value === "") { + return; + } - if (inputObject.value === '') { - return; - } + tempUrlGeneratorParams.append("object_name", inputObject.value); - tempUrlGeneratorParams.append('object_name', inputObject.value); + newButton.dataset.downloadButton = true; + newButton.dataset.key = inputKey.value; + newButton.dataset.iv = inputIv.value; + newButton.dataset.mimeType = inputType.value; + newButton.dataset.labelPreparing = labelPreparing; + newButton.dataset.labelReady = labelReady; + newButton.dataset.tempUrlGetGenerator = + tempUrlGenerator + "?" + tempUrlGeneratorParams.toString(); + newButton.classList.add("btn", "btn-download", "dz-bt-below-dropzone"); + newButton.textContent = labelQuietButton; - newButton.dataset.downloadButton = true; - newButton.dataset.key = inputKey.value; - newButton.dataset.iv = inputIv.value; - newButton.dataset.mimeType = inputType.value; - newButton.dataset.labelPreparing = labelPreparing; - newButton.dataset.labelReady = labelReady; - newButton.dataset.tempUrlGetGenerator = tempUrlGenerator + '?' + tempUrlGeneratorParams.toString(); - newButton.classList.add('btn', 'btn-download', 'dz-bt-below-dropzone'); - newButton.textContent = labelQuietButton; - - addBelowButton(newButton, zone, zoneData); - //zone.appendChild(newButton); - initializeButtons(zone); + addBelowButton(newButton, zone, zoneData); + //zone.appendChild(newButton); + initializeButtons(zone); }; -window.addEventListener('load', function(e) { - searchForZones(document); +window.addEventListener("load", function (e) { + searchForZones(document); }); -window.addEventListener('collection-add-entry', function(e) { - searchForZones(e.detail.entry); +window.addEventListener("collection-add-entry", function (e) { + searchForZones(e.detail.entry); }); export { searchForZones }; diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/module/document_action_buttons_group/index.ts b/src/Bundle/ChillDocStoreBundle/Resources/public/module/document_action_buttons_group/index.ts index 77eb8c2c9..38b2940b8 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/module/document_action_buttons_group/index.ts +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/module/document_action_buttons_group/index.ts @@ -1,53 +1,72 @@ -import {_createI18n} from "../../../../../ChillMainBundle/Resources/public/vuejs/_js/i18n"; +import { _createI18n } from "../../../../../ChillMainBundle/Resources/public/vuejs/_js/i18n"; import DocumentActionButtonsGroup from "../../vuejs/DocumentActionButtonsGroup.vue"; -import {createApp} from "vue"; -import {StoredObject, StoredObjectStatusChange} from "../../types"; -import {is_object_ready} from "../../vuejs/StoredObjectButton/helpers"; +import { createApp } from "vue"; +import { StoredObject, StoredObjectStatusChange } from "../../types"; +import { is_object_ready } from "../../vuejs/StoredObjectButton/helpers"; const i18n = _createI18n({}); -window.addEventListener('DOMContentLoaded', function (e) { - document.querySelectorAll('div[data-download-buttons]').forEach((el) => { - const app = createApp({ - components: {DocumentActionButtonsGroup}, - data() { +window.addEventListener("DOMContentLoaded", function (e) { + document + .querySelectorAll("div[data-download-buttons]") + .forEach((el) => { + const app = createApp({ + components: { DocumentActionButtonsGroup }, + data() { + const datasets = el.dataset as { + filename: string; + canEdit: string; + storedObject: string; + buttonSmall: string; + davLink: string; + davLinkExpiration: string; + }; - const datasets = el.dataset as { - filename: string, - canEdit: string, - storedObject: string, - buttonSmall: string, - davLink: string, - davLinkExpiration: string, - }; + const storedObject = JSON.parse( + datasets.storedObject, + ) as StoredObject, + filename = datasets.filename, + canEdit = datasets.canEdit === "1", + small = datasets.buttonSmall === "1", + davLink = + "davLink" in datasets && datasets.davLink !== "" + ? datasets.davLink + : null, + davLinkExpiration = + "davLinkExpiration" in datasets + ? Number.parseInt(datasets.davLinkExpiration) + : null; + return { + storedObject, + filename, + canEdit, + small, + davLink, + davLinkExpiration, + }; + }, + template: + '', + methods: { + onStoredObjectStatusChange: function ( + newStatus: StoredObjectStatusChange, + ): void { + this.$data.storedObject.status = newStatus.status; + this.$data.storedObject.filename = newStatus.filename; + this.$data.storedObject.type = newStatus.type; - const - storedObject = JSON.parse(datasets.storedObject) as StoredObject, - filename = datasets.filename, - canEdit = datasets.canEdit === '1', - small = datasets.buttonSmall === '1', - davLink = 'davLink' in datasets && datasets.davLink !== '' ? datasets.davLink : null, - davLinkExpiration = 'davLinkExpiration' in datasets ? Number.parseInt(datasets.davLinkExpiration) : null - ; + // remove eventual div which inform pending status + document + .querySelectorAll( + `[data-docgen-is-pending="${this.$data.storedObject.id}"]`, + ) + .forEach(function (el) { + el.remove(); + }); + }, + }, + }); - return { storedObject, filename, canEdit, small, davLink, davLinkExpiration }; - }, - template: '', - methods: { - onStoredObjectStatusChange: function(newStatus: StoredObjectStatusChange): void { - this.$data.storedObject.status = newStatus.status; - this.$data.storedObject.filename = newStatus.filename; - this.$data.storedObject.type = newStatus.type; - - // remove eventual div which inform pending status - document.querySelectorAll(`[data-docgen-is-pending="${this.$data.storedObject.id}"]`) - .forEach(function(el) { - el.remove(); - }); - } - } - }); - - app.use(i18n).mount(el); - }) + app.use(i18n).mount(el); + }); }); diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/types.ts b/src/Bundle/ChillDocStoreBundle/Resources/public/types.ts index 15644caf7..6667de484 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/types.ts +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/types.ts @@ -1,62 +1,61 @@ -import {DateTime} from "../../../ChillMainBundle/Resources/public/types"; +import { DateTime } from "../../../ChillMainBundle/Resources/public/types"; -export type StoredObjectStatus = "ready"|"failure"|"pending"; +export type StoredObjectStatus = "ready" | "failure" | "pending"; export interface StoredObject { - id: number, + id: number; - /** - * filename of the object in the object storage - */ - filename: string, - creationDate: DateTime, - datas: object, - iv: number[], - keyInfos: object, - title: string, - type: string, - uuid: string, - status: StoredObjectStatus, + /** + * filename of the object in the object storage + */ + filename: string; + creationDate: DateTime; + datas: object; + iv: number[]; + keyInfos: object; + title: string; + type: string; + uuid: string; + status: StoredObjectStatus; _links?: { - dav_link?: { - href: string - expiration: number - }, - } + dav_link?: { + href: string; + expiration: number; + }; + }; } export interface StoredObjectCreated { - status: "stored_object_created", - filename: string, - iv: Uint8Array, - keyInfos: object, - type: string, + status: "stored_object_created"; + filename: string; + iv: Uint8Array; + keyInfos: object; + type: string; } export interface StoredObjectStatusChange { - id: number, - filename: string, - status: StoredObjectStatus, - type: string, + id: number; + filename: string; + status: StoredObjectStatus; + type: string; } /** * Function executed by the WopiEditButton component. */ -export type WopiEditButtonExecutableBeforeLeaveFunction = () => Promise +export type WopiEditButtonExecutableBeforeLeaveFunction = () => Promise; /** * Object containing information for performering a POST request to a swift object store */ export interface PostStoreObjectSignature { - method: "POST", - max_file_size: number, - max_file_count: 1, - expires: number, - submit_delay: 180, - redirect: string, - prefix: string, - url: string, - signature: string, + method: "POST"; + max_file_size: number; + max_file_count: 1; + expires: number; + submit_delay: 180; + redirect: string; + prefix: string; + url: string; + signature: string; } - diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DocumentActionButtonsGroup.vue b/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DocumentActionButtonsGroup.vue index 5f234d099..392920ea1 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DocumentActionButtonsGroup.vue +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DocumentActionButtonsGroup.vue @@ -1,86 +1,152 @@ - + diff --git a/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DropFileWidget/DropFile.vue b/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DropFileWidget/DropFile.vue index 67064ea34..cba1a3951 100644 --- a/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DropFileWidget/DropFile.vue +++ b/src/Bundle/ChillDocStoreBundle/Resources/public/vuejs/DropFileWidget/DropFile.vue @@ -1,20 +1,22 @@ - - - - - - - - - - - + + + + + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMap.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMap.vue index 133c94dcf..167b3b981 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMap.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMap.vue @@ -1,99 +1,119 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMore.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMore.vue index e4b4e94e0..4b59efbc6 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMore.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressMore.vue @@ -1,158 +1,149 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressSelection.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressSelection.vue index 7dcdf1ad9..fd1740a40 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressSelection.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/AddressSelection.vue @@ -1,204 +1,227 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CitySelection.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CitySelection.vue index 90fb47af6..0d85c69f9 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CitySelection.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CitySelection.vue @@ -1,221 +1,251 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CountrySelection.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CountrySelection.vue index d8578dab7..71e24bd24 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CountrySelection.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/AddAddress/CountrySelection.vue @@ -1,76 +1,86 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/DatePane.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/DatePane.vue index 9ebb78c9d..96e67f952 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/DatePane.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/DatePane.vue @@ -1,166 +1,187 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/EditPane.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/EditPane.vue index 375e2ff4c..df5ea56dc 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/EditPane.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/EditPane.vue @@ -1,216 +1,197 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/ShowPane.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/ShowPane.vue index e54cf0f56..a17ce719d 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/ShowPane.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/ShowPane.vue @@ -1,199 +1,213 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/SuggestPane.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/SuggestPane.vue index 3ccf59358..ddaed6219 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/SuggestPane.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/components/SuggestPane.vue @@ -1,100 +1,94 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/i18n.js b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/i18n.js index 28670f56c..546232055 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/i18n.js +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/i18n.js @@ -1,56 +1,56 @@ -import { multiSelectMessages } from 'ChillMainAssets/vuejs/_js/i18n' +import { multiSelectMessages } from "ChillMainAssets/vuejs/_js/i18n"; const addressMessages = { - fr: { - add_an_address_title: 'Créer une adresse', - edit_an_address_title: 'Modifier une adresse', - create_a_new_address: 'Créer une nouvelle adresse', - edit_address: 'Modifier l\'adresse', - select_an_address_title: 'Sélectionner une adresse', - fill_an_address: 'Compléter l\'adresse', - select_country: 'Choisir le pays', - country: 'Pays', - select_city: 'Choisir une localité', - city: 'Localité', - other_city: 'Autre localité', - select_address: 'Choisir une adresse', - address: 'Adresse', - other_address: 'Autre adresse', - create_address: 'Adresse inconnue. Cliquez ici pour créer une nouvelle adresse', - isNoAddress: 'Pas d\'adresse complète', - isConfidential: 'Adresse confidentielle', - street: 'Nom de rue', - streetNumber: 'Numéro', - floor: 'Étage', - corridor: 'Couloir', - steps: 'Escalier', - flat: 'Appartement', - buildingName: 'Résidence', - extra: 'Complément d\'adresse', - distribution: 'Cedex', - create_postal_code: 'Localité inconnue. Cliquez ici pour créer une nouvelle localité', - postalCode_name: 'Nom', - postalCode_code: 'Code postal', - date: "Date de la nouvelle adresse", - validFrom: "L'adresse est valable à partir du", - validTo: "L'adresse est valable jusqu'au", - back_to_the_list: 'Retour à la liste', - loading: 'chargement en cours...', - address_suggestions: "Suggestion d'adresses", - address_new_success: 'La nouvelle adresse est enregistrée.', - address_edit_success: 'L\'adresse a été mise à jour.', - wait_redirection: " La page est redirigée.", - not_yet_address: "Il n'y a pas encore d'adresse. Cliquez sur '+ Créer une adresse'", - use_this_address: "Utiliser cette adresse", + fr: { + add_an_address_title: "Créer une adresse", + edit_an_address_title: "Modifier une adresse", + create_a_new_address: "Créer une nouvelle adresse", + edit_address: "Modifier l'adresse", + select_an_address_title: "Sélectionner une adresse", + fill_an_address: "Compléter l'adresse", + select_country: "Choisir le pays", + country: "Pays", + select_city: "Choisir une localité", + city: "Localité", + other_city: "Autre localité", + select_address: "Choisir une adresse", + address: "Adresse", + other_address: "Autre adresse", + create_address: + "Adresse inconnue. Cliquez ici pour créer une nouvelle adresse", + isNoAddress: "Pas d'adresse complète", + isConfidential: "Adresse confidentielle", + street: "Nom de rue", + streetNumber: "Numéro", + floor: "Étage", + corridor: "Couloir", + steps: "Escalier", + flat: "Appartement", + buildingName: "Résidence", + extra: "Complément d'adresse", + distribution: "Cedex", + create_postal_code: + "Localité inconnue. Cliquez ici pour créer une nouvelle localité", + postalCode_name: "Nom", + postalCode_code: "Code postal", + date: "Date de la nouvelle adresse", + validFrom: "L'adresse est valable à partir du", + validTo: "L'adresse est valable jusqu'au", + back_to_the_list: "Retour à la liste", + loading: "chargement en cours...", + address_suggestions: "Suggestion d'adresses", + address_new_success: "La nouvelle adresse est enregistrée.", + address_edit_success: "L'adresse a été mise à jour.", + wait_redirection: " La page est redirigée.", + not_yet_address: + "Il n'y a pas encore d'adresse. Cliquez sur '+ Créer une adresse'", + use_this_address: "Utiliser cette adresse", - // household specific - move_date: 'Date du déménagement', - - } + // household specific + move_date: "Date du déménagement", + }, }; Object.assign(addressMessages.fr, multiSelectMessages.fr); -export { - addressMessages -}; +export { addressMessages }; diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/index.js b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/index.js index ab0fb0bd4..58c20366a 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/index.js +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/index.js @@ -1,68 +1,67 @@ -import { createApp } from 'vue'; -import { _createI18n } from 'ChillMainAssets/vuejs/_js/i18n'; -import { addressMessages } from './i18n'; -import App from './App.vue'; +import { createApp } from "vue"; +import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n"; +import { addressMessages } from "./i18n"; +import App from "./App.vue"; -const i18n = _createI18n( addressMessages ); +const i18n = _createI18n(addressMessages); -let containers = document.querySelectorAll('.address-container'); +let containers = document.querySelectorAll(".address-container"); containers.forEach((container) => { + const app = createApp({ + template: ``, + data() { + return { + addAddress: { + context: { + target: { + name: container.dataset.targetName, + id: parseInt(container.dataset.targetId), + }, + edit: container.dataset.mode === "edit", //boolean + addressId: parseInt(container.dataset.addressId) || null, + backUrl: container.dataset.backUrl || null, + defaults: JSON.parse(container.dataset.addressDefaults), + }, + options: { + /// Options override default. + /// null value take default component value defined in AddAddress data() + button: { + text: { + create: container.dataset.buttonText || null, + edit: container.dataset.buttonText || null, + }, + size: container.dataset.buttonSize || null, + displayText: container.dataset.buttonDisplayText !== "false", //boolean, default: true + }, - const app = createApp({ - template: ``, - data() { - return { - addAddress: { - context: { - target: { - name: container.dataset.targetName, - id: parseInt(container.dataset.targetId) - }, - edit: container.dataset.mode === 'edit', //boolean - addressId: parseInt(container.dataset.addressId) || null, - backUrl: container.dataset.backUrl || null, - defaults: JSON.parse(container.dataset.addressDefaults) - }, - options: { - /// Options override default. - /// null value take default component value defined in AddAddress data() - button: { - text: { - create: container.dataset.buttonText || null, - edit: container.dataset.buttonText || null - }, - size: container.dataset.buttonSize || null, - displayText: container.dataset.buttonDisplayText !== 'false' //boolean, default: true - }, + /// Modal title text if create or edit address (trans chain, see i18n) + title: { + create: container.dataset.modalTitle || null, + edit: container.dataset.modalTitle || null, + }, - /// Modal title text if create or edit address (trans chain, see i18n) - title: { - create: container.dataset.modalTitle || null, - edit: container.dataset.modalTitle || null - }, + /// Display panes in Modal for step123 + openPanesInModal: container.dataset.openPanesInModal !== "false", //boolean, default: true - /// Display panes in Modal for step123 - openPanesInModal: container.dataset.openPanesInModal !== 'false', //boolean, default: true + /// Display actions buttons of panes in a sticky-form-button navbar + stickyActions: container.dataset.stickyActions === "true", //boolean, default: false - /// Display actions buttons of panes in a sticky-form-button navbar - stickyActions: container.dataset.stickyActions === 'true', //boolean, default: false + /// Use Date fields + useDate: { + validFrom: container.dataset.useValidFrom === "true", //boolean, default: false + validTo: container.dataset.useValidTo === "true", //boolean, default: false + }, - /// Use Date fields - useDate: { - validFrom: container.dataset.useValidFrom === 'true', //boolean, default: false - validTo: container.dataset.useValidTo === 'true' //boolean, default: false - }, - - /// Don't display show renderbox Address: showPane display only a button - onlyButton: container.dataset.onlyButton === 'true' //boolean, default: false - } - } - } - } - }) + /// Don't display show renderbox Address: showPane display only a button + onlyButton: container.dataset.onlyButton === "true", //boolean, default: false + }, + }, + }; + }, + }) .use(i18n) - .component('app', App) + .component("app", App) .mount(container); - //console.log('container dataset', container.dataset); + //console.log('container dataset', container.dataset); }); diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/mod_input_address_index.js b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/mod_input_address_index.js index 66d649c14..3f6af7a6e 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/mod_input_address_index.js +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/mod_input_address_index.js @@ -1,93 +1,96 @@ -import {createApp} from 'vue'; -import {_createI18n} from 'ChillMainAssets/vuejs/_js/i18n'; -import {addressMessages} from './i18n'; -import App from './App.vue'; +import { createApp } from "vue"; +import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n"; +import { addressMessages } from "./i18n"; +import App from "./App.vue"; const i18n = _createI18n(addressMessages); const addAddressInput = (inputs) => { - console.log(inputs) - inputs.forEach(el => { - let - addressId = el.value, - uniqid = el.dataset.inputAddress, - container = el.parentNode.querySelector('div[data-input-address-container="' + uniqid + '"]'), - isEdit = addressId !== '', - addressIdInt = addressId !== '' ? parseInt(addressId) : null - ; - - if (container === null) { - throw Error("no container"); - } -/* exported app */ - const app = createApp({ - template: ``, - data() { - return { - addAddress: { - context: { - // for legacy ? can be remove ? - target: { - name: 'input-address', - id: addressIdInt, - }, - edit: isEdit, - addressId: addressIdInt, - defaults: window.addaddress, - }, - options: { - /// Options override default. - /// null value take default component value defined in AddAddress data() - button: { - text: { - create: el.dataset.buttonTextCreate || null, - edit: el.dataset.buttonTextUpdate || null, - }, - size: null, - displayText: true - }, - - /// Modal title text if create or edit address (trans chain, see i18n) - title: { - create: null, - edit: null, - }, - - /// Display panes in Modal for step123 - openPanesInModal: true, - - /// Display actions buttons of panes in a sticky-form-button navbar - stickyActions: false, - showMessageWhenNoAddress: true, - - /// Use Date fields - useDate: { - validFrom: el.dataset.useValidFrom === '1' || false, //boolean, default: false - validTo: el.dataset.useValidTo === '1' || false, //boolean, default: false - }, - - /// Don't display show renderbox Address: showPane display only a button - onlyButton: false, - } - } - } + console.log(inputs); + inputs.forEach((el) => { + let addressId = el.value, + uniqid = el.dataset.inputAddress, + container = el.parentNode.querySelector( + 'div[data-input-address-container="' + uniqid + '"]', + ), + isEdit = addressId !== "", + addressIdInt = addressId !== "" ? parseInt(addressId) : null; + if (container === null) { + throw Error("no container"); + } + /* exported app */ + const app = createApp({ + template: ``, + data() { + return { + addAddress: { + context: { + // for legacy ? can be remove ? + target: { + name: "input-address", + id: addressIdInt, + }, + edit: isEdit, + addressId: addressIdInt, + defaults: window.addaddress, }, - methods: { - associateToInput(payload) { - el.value = payload.addressId; - } - } - }) - .use(i18n) - .component('app', App) - .mount(container); - }); + options: { + /// Options override default. + /// null value take default component value defined in AddAddress data() + button: { + text: { + create: el.dataset.buttonTextCreate || null, + edit: el.dataset.buttonTextUpdate || null, + }, + size: null, + displayText: true, + }, + + /// Modal title text if create or edit address (trans chain, see i18n) + title: { + create: null, + edit: null, + }, + + /// Display panes in Modal for step123 + openPanesInModal: true, + + /// Display actions buttons of panes in a sticky-form-button navbar + stickyActions: false, + showMessageWhenNoAddress: true, + + /// Use Date fields + useDate: { + validFrom: el.dataset.useValidFrom === "1" || false, //boolean, default: false + validTo: el.dataset.useValidTo === "1" || false, //boolean, default: false + }, + + /// Don't display show renderbox Address: showPane display only a button + onlyButton: false, + }, + }, + }; + }, + methods: { + associateToInput(payload) { + el.value = payload.addressId; + }, + }, + }) + .use(i18n) + .component("app", App) + .mount(container); + }); }; -document.addEventListener('DOMContentLoaded', (_e) => - addAddressInput(document.querySelectorAll('input[type="hidden"][data-input-address]')) +document.addEventListener("DOMContentLoaded", (_e) => + addAddressInput( + document.querySelectorAll('input[type="hidden"][data-input-address]'), + ), ); -window.addEventListener('collection-add-entry', (e) => - addAddressInput(e.detail.entry.querySelectorAll('input[type="hidden"][data-input-address]')) +window.addEventListener("collection-add-entry", (e) => + addAddressInput( + e.detail.entry.querySelectorAll('input[type="hidden"][data-input-address]'), + ), ); diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/store.js b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/store.js index 392d033f5..91765c671 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/store.js +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/Address/store.js @@ -1,14 +1,14 @@ -import 'es6-promise/auto'; -import { createStore } from 'vuex'; +import "es6-promise/auto"; +import { createStore } from "vuex"; -const debug = process.env.NODE_ENV !== 'production'; +const debug = process.env.NODE_ENV !== "production"; const store = createStore({ - strict: debug, - state: {}, - getters: {}, - mutations: {}, - actions: {}, + strict: debug, + state: {}, + getters: {}, + mutations: {}, + actions: {}, }); export { store }; diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/App.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/App.vue index 41f1411a3..8686b59a7 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/App.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/App.vue @@ -1,36 +1,36 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/News.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/News.vue index 2802f5864..5633d3133 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/News.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/News.vue @@ -1,24 +1,25 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/NewsItem.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/NewsItem.vue index 776476768..997eae58b 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/NewsItem.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/DashboardWidgets/NewsItem.vue @@ -1,11 +1,18 @@ @@ -28,18 +39,17 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyAccompanyingCourses.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyAccompanyingCourses.vue index d605b7fda..d692e348d 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyAccompanyingCourses.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyAccompanyingCourses.vue @@ -1,116 +1,110 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyCustoms.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyCustoms.vue index 0246aa357..1f76a5a0a 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyCustoms.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyCustoms.vue @@ -1,158 +1,158 @@ + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyNotifications.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyNotifications.vue index 7d9dcc885..377903c01 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyNotifications.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyNotifications.vue @@ -1,129 +1,117 @@ \ No newline at end of file + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyTasks.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyTasks.vue index 6ba176f7f..ca30197a8 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyTasks.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyTasks.vue @@ -1,90 +1,83 @@ \ No newline at end of file + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflows.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflows.vue index 78ccc78cf..68ac0bc1e 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflows.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflows.vue @@ -1,29 +1,26 @@ \ No newline at end of file +}; + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflowsTable.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflowsTable.vue index 15337aaf0..68dac9999 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflowsTable.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/MyWorkflowsTable.vue @@ -1,79 +1,68 @@ \ No newline at end of file + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabCounter.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabCounter.vue index 1f113b547..daec6db4a 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabCounter.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabCounter.vue @@ -1,20 +1,17 @@ \ No newline at end of file + name: "TabCounter", + props: ["count"], + computed: { + isCounterAvailable() { + return typeof this.count !== "undefined" && this.count > 0; + }, + }, +}; + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabTable.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabTable.vue index 1f6c66677..c8899aa86 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabTable.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/TabTable.vue @@ -1,21 +1,21 @@ - \ No newline at end of file + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/i18n.js b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/i18n.js index ddc1b55ef..5ccea9528 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/i18n.js +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/i18n.js @@ -1,82 +1,88 @@ const appMessages = { - fr: { - main_title: "Vue d'ensemble", - my_works: { - tab: "Mes actions", - description: "Liste des actions d'accompagnement dont je suis référent et qui arrivent à échéance.", - }, - my_evaluations: { - tab: "Mes évaluations", - description: "Liste des évaluations dont je suis référent et qui arrivent à échéance.", - }, - my_tasks: { - tab: "Mes tâches", - description_alert: "Liste des tâches auxquelles je suis assigné et dont la date de rappel est dépassée.", - description_warning: "Liste des tâches auxquelles je suis assigné et dont la date d'échéance est dépassée.", - }, - my_accompanying_courses: { - tab: "Mes nouveaux parcours", - description: "Liste des parcours d'accompagnement que l'on vient de m'attribuer depuis moins de 15 jours.", - }, - my_notifications: { - tab: "Mes nouvelles notifications", - description: "Liste des notifications reçues et non lues.", - }, - my_workflows: { - tab: "Mes workflows", - description: "Liste des workflows en attente d'une action.", - description_cc: "Liste des workflows dont je suis en copie." - }, - opening_date: "Date d'ouverture", - social_issues: "Problématiques sociales", - concerned_persons: "Usagers concernés", - max_date: "Date d'échéance", - warning_date: "Date de rappel", - evaluation: "Évaluation", - task: "Tâche", - Date: "Date", - From: "Expéditeur", - Subject: "Objet", - Entity: "Associé à", - Step: "Étape", - concerned_users: "Usagers concernés", - Object_workflow: "Objet du workflow", - show_entity: "Voir {entity}", - the_activity: "l'échange", - the_course: "le parcours", - the_action: "l'action", - the_evaluation: "l'évaluation", - the_evaluation_document: "le document", - the_task: "la tâche", - the_workflow: "le workflow", - StartDate: "Date d'ouverture", - SocialAction: "Action d'accompagnement", - no_data: "Aucun résultats", - no_dashboard: "Pas de tableaux de bord", - counter: { - unread_notifications: "{n} notification non lue | {n} notifications non lues", - assignated_courses: "{n} parcours récent assigné | {n} parcours récents assignés", - assignated_actions: "{n} action assignée | {n} actions assignées", - assignated_evaluations: "{n} évaluation assignée | {n} évaluations assignées", - alert_tasks: "{n} tâche en rappel | {n} tâches en rappel", - warning_tasks: "{n} tâche à échéance | {n} tâches à échéance", - }, - emergency: "Urgent", - confidential: "Confidentiel", - automatic_notification: "Notification automatique", - widget: { - news: { - title: "Actualités", - readMore: "Lire la suite", - date: "Date", - none: "Aucune actualité" - } - } - } + fr: { + main_title: "Vue d'ensemble", + my_works: { + tab: "Mes actions", + description: + "Liste des actions d'accompagnement dont je suis référent et qui arrivent à échéance.", + }, + my_evaluations: { + tab: "Mes évaluations", + description: + "Liste des évaluations dont je suis référent et qui arrivent à échéance.", + }, + my_tasks: { + tab: "Mes tâches", + description_alert: + "Liste des tâches auxquelles je suis assigné et dont la date de rappel est dépassée.", + description_warning: + "Liste des tâches auxquelles je suis assigné et dont la date d'échéance est dépassée.", + }, + my_accompanying_courses: { + tab: "Mes nouveaux parcours", + description: + "Liste des parcours d'accompagnement que l'on vient de m'attribuer depuis moins de 15 jours.", + }, + my_notifications: { + tab: "Mes nouvelles notifications", + description: "Liste des notifications reçues et non lues.", + }, + my_workflows: { + tab: "Mes workflows", + description: "Liste des workflows en attente d'une action.", + description_cc: "Liste des workflows dont je suis en copie.", + }, + opening_date: "Date d'ouverture", + social_issues: "Problématiques sociales", + concerned_persons: "Usagers concernés", + max_date: "Date d'échéance", + warning_date: "Date de rappel", + evaluation: "Évaluation", + task: "Tâche", + Date: "Date", + From: "Expéditeur", + Subject: "Objet", + Entity: "Associé à", + Step: "Étape", + concerned_users: "Usagers concernés", + Object_workflow: "Objet du workflow", + show_entity: "Voir {entity}", + the_activity: "l'échange", + the_course: "le parcours", + the_action: "l'action", + the_evaluation: "l'évaluation", + the_evaluation_document: "le document", + the_task: "la tâche", + the_workflow: "le workflow", + StartDate: "Date d'ouverture", + SocialAction: "Action d'accompagnement", + no_data: "Aucun résultats", + no_dashboard: "Pas de tableaux de bord", + counter: { + unread_notifications: + "{n} notification non lue | {n} notifications non lues", + assignated_courses: + "{n} parcours récent assigné | {n} parcours récents assignés", + assignated_actions: "{n} action assignée | {n} actions assignées", + assignated_evaluations: + "{n} évaluation assignée | {n} évaluations assignées", + alert_tasks: "{n} tâche en rappel | {n} tâches en rappel", + warning_tasks: "{n} tâche à échéance | {n} tâches à échéance", + }, + emergency: "Urgent", + confidential: "Confidentiel", + automatic_notification: "Notification automatique", + widget: { + news: { + title: "Actualités", + readMore: "Lire la suite", + date: "Date", + none: "Aucune actualité", + }, + }, + }, }; Object.assign(appMessages.fr); -export { - appMessages -}; +export { appMessages }; diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/store.js b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/store.js index 1579a3d0c..ed88b857d 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/store.js +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/HomepageWidget/js/store.js @@ -1,226 +1,222 @@ -import 'es6-promise/auto'; -import { createStore } from 'vuex'; +import "es6-promise/auto"; +import { createStore } from "vuex"; import { makeFetch } from "ChillMainAssets/lib/api/apiMethods"; -const debug = process.env.NODE_ENV !== 'production'; +const debug = process.env.NODE_ENV !== "production"; const isEmpty = (obj) => { - return obj - && Object.keys(obj).length <= 1 - && Object.getPrototypeOf(obj) === Object.prototype; + return ( + obj && + Object.keys(obj).length <= 1 && + Object.getPrototypeOf(obj) === Object.prototype + ); }; const store = createStore({ - strict: debug, - state: { - // works: {}, - evaluations: {}, - tasks: { - warning: {}, - alert: {} - }, - accompanyingCourses: {}, - notifications: {}, - workflows: {}, - workflowsCc: {}, - errorMsg: [], - loading: false + strict: debug, + state: { + // works: {}, + evaluations: {}, + tasks: { + warning: {}, + alert: {}, }, - getters: { - // isWorksLoaded(state) { - // return !isEmpty(state.works); - // }, - isEvaluationsLoaded(state) { - return !isEmpty(state.evaluations); - }, - isTasksWarningLoaded(state) { - return !isEmpty(state.tasks.warning); - }, - isTasksAlertLoaded(state) { - return !isEmpty(state.tasks.alert); - }, - isAccompanyingCoursesLoaded(state) { - return !isEmpty(state.accompanyingCourses); - }, - isNotificationsLoaded(state) { - return !isEmpty(state.notifications); - }, - isWorkflowsLoaded(state) { - return !isEmpty(state.workflows); - }, - counter(state) { - return { - // works: state.works.count, - evaluations: state.evaluations.count, - tasksWarning: state.tasks.warning.count, - tasksAlert: state.tasks.alert.count, - accompanyingCourses: state.accompanyingCourses.count, - notifications: state.notifications.count, - workflows: state.workflows.count - } - } + accompanyingCourses: {}, + notifications: {}, + workflows: {}, + workflowsCc: {}, + errorMsg: [], + loading: false, + }, + getters: { + // isWorksLoaded(state) { + // return !isEmpty(state.works); + // }, + isEvaluationsLoaded(state) { + return !isEmpty(state.evaluations); }, - mutations: { - // addWorks(state, works) { - // //console.log('addWorks', works); - // state.works = works; - // }, - addEvaluations(state, evaluations) { - //console.log('addEvaluations', evaluations); - state.evaluations = evaluations; - }, - addTasksWarning(state, tasks) { - //console.log('addTasksWarning', tasks); - state.tasks.warning = tasks; - }, - addTasksAlert(state, tasks) { - //console.log('addTasksAlert', tasks); - state.tasks.alert = tasks; - }, - addCourses(state, courses) { - //console.log('addCourses', courses); - state.accompanyingCourses = courses; - }, - addNotifications(state, notifications) { - //console.log('addNotifications', notifications); - state.notifications = notifications; - }, - addWorkflows(state, workflows) { - state.workflows = workflows; - }, - addWorkflowsCc(state, workflows) { - state.workflowsCc = workflows; - }, - setLoading(state, bool) { - state.loading = bool; - }, - catchError(state, error) { - state.errorMsg.push(error); - }, + isTasksWarningLoaded(state) { + return !isEmpty(state.tasks.warning); }, - actions: { - getByTab({ commit, getters }, { tab, param }) { - switch (tab) { - // case 'MyWorks': - // if (!getters.isWorksLoaded) { - // commit('setLoading', true); - // const url = `/api/1.0/person/accompanying-period/work/my-near-end${'?'+ param}`; - // makeFetch('GET', url) - // .then((response) => { - // commit('addWorks', response); - // commit('setLoading', false); - // }) - // .catch((error) => { - // commit('catchError', error); - // throw error; - // }) - // ; - // } - // break; - case 'MyEvaluations': - if (!getters.isEvaluationsLoaded) { - commit('setLoading', true); - const url = `/api/1.0/person/accompanying-period/work/evaluation/my-near-end${'?'+ param}`; - makeFetch('GET', url) - .then((response) => { - commit('addEvaluations', response); - commit('setLoading', false); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) - ; - } - break; - case 'MyTasks': - if (!(getters.isTasksWarningLoaded && getters.isTasksAlertLoaded)) { - commit('setLoading', true); - const - urlWarning = `/api/1.0/task/single-task/list/my?f[q]=&f[checkboxes][status][]=warning&f[checkboxes][states][]=new&f[checkboxes][states][]=in_progress${'&'+ param}`, - urlAlert = `/api/1.0/task/single-task/list/my?f[q]=&f[checkboxes][status][]=alert&f[checkboxes][states][]=new&f[checkboxes][states][]=in_progress${'&'+ param}` - ; - makeFetch('GET', urlWarning) - .then((response) => { - commit('addTasksWarning', response); - commit('setLoading', false); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) - ; - makeFetch('GET', urlAlert) - .then((response) => { - commit('addTasksAlert', response); - commit('setLoading', false); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) - ; - } - break; - case 'MyAccompanyingCourses': - if (!getters.isAccompanyingCoursesLoaded) { - commit('setLoading', true); - const url = `/api/1.0/person/accompanying-course/list/by-recent-attributions${'?'+ param}`; - makeFetch('GET', url) - .then((response) => { - commit('addCourses', response); - commit('setLoading', false); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) - ; - } - break; - case 'MyNotifications': - if (!getters.isNotificationsLoaded) { - commit('setLoading', true); - const url = `/api/1.0/main/notification/my/unread${'?'+ param}`; - makeFetch('GET', url) - .then((response) => { - console.log('notifications', response) - commit('addNotifications', response); - commit('setLoading', false); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }); - } - break; - case 'MyWorkflows': - if (!getters.isWorflowsLoaded) { - commit('setLoading', true); - makeFetch('GET', '/api/1.0/main/workflow/my') - .then((response) => { - commit('addWorkflows', response); - makeFetch('GET', '/api/1.0/main/workflow/my-cc') - .then((response) => { - commit('addWorkflowsCc', response); - commit('setLoading', false); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }); - } - break; - default: - throw 'tab '+ tab; - } - }, + isTasksAlertLoaded(state) { + return !isEmpty(state.tasks.alert); }, + isAccompanyingCoursesLoaded(state) { + return !isEmpty(state.accompanyingCourses); + }, + isNotificationsLoaded(state) { + return !isEmpty(state.notifications); + }, + isWorkflowsLoaded(state) { + return !isEmpty(state.workflows); + }, + counter(state) { + return { + // works: state.works.count, + evaluations: state.evaluations.count, + tasksWarning: state.tasks.warning.count, + tasksAlert: state.tasks.alert.count, + accompanyingCourses: state.accompanyingCourses.count, + notifications: state.notifications.count, + workflows: state.workflows.count, + }; + }, + }, + mutations: { + // addWorks(state, works) { + // //console.log('addWorks', works); + // state.works = works; + // }, + addEvaluations(state, evaluations) { + //console.log('addEvaluations', evaluations); + state.evaluations = evaluations; + }, + addTasksWarning(state, tasks) { + //console.log('addTasksWarning', tasks); + state.tasks.warning = tasks; + }, + addTasksAlert(state, tasks) { + //console.log('addTasksAlert', tasks); + state.tasks.alert = tasks; + }, + addCourses(state, courses) { + //console.log('addCourses', courses); + state.accompanyingCourses = courses; + }, + addNotifications(state, notifications) { + //console.log('addNotifications', notifications); + state.notifications = notifications; + }, + addWorkflows(state, workflows) { + state.workflows = workflows; + }, + addWorkflowsCc(state, workflows) { + state.workflowsCc = workflows; + }, + setLoading(state, bool) { + state.loading = bool; + }, + catchError(state, error) { + state.errorMsg.push(error); + }, + }, + actions: { + getByTab({ commit, getters }, { tab, param }) { + switch (tab) { + // case 'MyWorks': + // if (!getters.isWorksLoaded) { + // commit('setLoading', true); + // const url = `/api/1.0/person/accompanying-period/work/my-near-end${'?'+ param}`; + // makeFetch('GET', url) + // .then((response) => { + // commit('addWorks', response); + // commit('setLoading', false); + // }) + // .catch((error) => { + // commit('catchError', error); + // throw error; + // }) + // ; + // } + // break; + case "MyEvaluations": + if (!getters.isEvaluationsLoaded) { + commit("setLoading", true); + const url = `/api/1.0/person/accompanying-period/work/evaluation/my-near-end${"?" + param}`; + makeFetch("GET", url) + .then((response) => { + commit("addEvaluations", response); + commit("setLoading", false); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + } + break; + case "MyTasks": + if (!(getters.isTasksWarningLoaded && getters.isTasksAlertLoaded)) { + commit("setLoading", true); + const urlWarning = `/api/1.0/task/single-task/list/my?f[q]=&f[checkboxes][status][]=warning&f[checkboxes][states][]=new&f[checkboxes][states][]=in_progress${"&" + param}`, + urlAlert = `/api/1.0/task/single-task/list/my?f[q]=&f[checkboxes][status][]=alert&f[checkboxes][states][]=new&f[checkboxes][states][]=in_progress${"&" + param}`; + makeFetch("GET", urlWarning) + .then((response) => { + commit("addTasksWarning", response); + commit("setLoading", false); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + makeFetch("GET", urlAlert) + .then((response) => { + commit("addTasksAlert", response); + commit("setLoading", false); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + } + break; + case "MyAccompanyingCourses": + if (!getters.isAccompanyingCoursesLoaded) { + commit("setLoading", true); + const url = `/api/1.0/person/accompanying-course/list/by-recent-attributions${"?" + param}`; + makeFetch("GET", url) + .then((response) => { + commit("addCourses", response); + commit("setLoading", false); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + } + break; + case "MyNotifications": + if (!getters.isNotificationsLoaded) { + commit("setLoading", true); + const url = `/api/1.0/main/notification/my/unread${"?" + param}`; + makeFetch("GET", url) + .then((response) => { + console.log("notifications", response); + commit("addNotifications", response); + commit("setLoading", false); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + } + break; + case "MyWorkflows": + if (!getters.isWorflowsLoaded) { + commit("setLoading", true); + makeFetch("GET", "/api/1.0/main/workflow/my") + .then((response) => { + commit("addWorkflows", response); + makeFetch("GET", "/api/1.0/main/workflow/my-cc") + .then((response) => { + commit("addWorkflowsCc", response); + commit("setLoading", false); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + } + break; + default: + throw "tab " + tab; + } + }, + }, }); export { store }; diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/App.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/App.vue index 5acd992bc..24c5421a8 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/App.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/App.vue @@ -1,32 +1,32 @@ - diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/Create.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/Create.vue index 9823a5818..9a4325060 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/Create.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/Create.vue @@ -1,121 +1,113 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/OnTheFly.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/OnTheFly.vue index 11c1c33b7..452ac0396 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/OnTheFly.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/OnTheFly/components/OnTheFly.vue @@ -1,314 +1,328 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressDetailsContent.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressDetailsContent.vue index 5c67e783c..41bb00025 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressDetailsContent.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressDetailsContent.vue @@ -1,31 +1,36 @@ - + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressModal.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressModal.vue index aac856a23..7c00066be 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressModal.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/AddressModal.vue @@ -1,55 +1,55 @@ - + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsGeographicalLayers.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsGeographicalLayers.vue index 02db658b6..aac5fd1d7 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsGeographicalLayers.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsGeographicalLayers.vue @@ -1,55 +1,59 @@ - + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsMap.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsMap.vue index fd652a5f9..3fe075fcc 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsMap.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsMap.vue @@ -1,90 +1,108 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsRefMatching.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsRefMatching.vue index 367f465f8..c3d421411 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsRefMatching.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/AddressDetails/Parts/AddressDetailsRefMatching.vue @@ -1,94 +1,179 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/BadgeEntity.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/BadgeEntity.vue index d72758400..0c4c1cb30 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/BadgeEntity.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/BadgeEntity.vue @@ -1,58 +1,47 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Confidential.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Confidential.vue index 5cffd2ccd..13459b390 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Confidential.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Confidential.vue @@ -1,17 +1,17 @@ - diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/AddressRenderBox.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/AddressRenderBox.vue index fb9cde4fc..71b7af390 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/AddressRenderBox.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/AddressRenderBox.vue @@ -1,150 +1,131 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/GenderIconRenderBox.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/GenderIconRenderBox.vue index afbf3586f..d47b9b777 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/GenderIconRenderBox.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/GenderIconRenderBox.vue @@ -1,11 +1,9 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/UserRenderBoxBadge.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/UserRenderBoxBadge.vue index 5b10027a4..2ccfa7b99 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/UserRenderBoxBadge.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Entity/UserRenderBoxBadge.vue @@ -1,23 +1,24 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/EntityWorkflowVueSubscriber.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/EntityWorkflowVueSubscriber.vue index a890a2ad4..50cf1f7b8 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/EntityWorkflowVueSubscriber.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/EntityWorkflowVueSubscriber.vue @@ -1,58 +1,61 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/ListWorkflowModal.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/ListWorkflowModal.vue index 72e4dadb4..9fdba0b10 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/ListWorkflowModal.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/ListWorkflowModal.vue @@ -1,140 +1,140 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/PickWorkflow.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/PickWorkflow.vue index 0c804f678..606e18d65 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/PickWorkflow.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/EntityWorkflow/PickWorkflow.vue @@ -1,37 +1,31 @@ - + diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Modal.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Modal.vue index bf4d12eca..63899161d 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Modal.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Modal.vue @@ -1,58 +1,46 @@ diff --git a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Notification/NotificationReadAllToggle.vue b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Notification/NotificationReadAllToggle.vue index d5dd37237..57f7fd7f8 100644 --- a/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Notification/NotificationReadAllToggle.vue +++ b/src/Bundle/ChillMainBundle/Resources/public/vuejs/_components/Notification/NotificationReadAllToggle.vue @@ -1,17 +1,14 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/api.js b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/api.js index 6912c68ae..6eb2473de 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/api.js +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/api.js @@ -1,52 +1,73 @@ -import { fetchResults } from 'ChillMainAssets/lib/api/apiMethods.ts'; +import { fetchResults } from "ChillMainAssets/lib/api/apiMethods.ts"; /* -* Endpoint v.2 chill_api_single_accompanying_course__entity -* method GET/HEAD, get AccompanyingCourse Instance -* -* @id integer - id of accompanyingCourse -*/ + * Endpoint v.2 chill_api_single_accompanying_course__entity + * method GET/HEAD, get AccompanyingCourse Instance + * + * @id integer - id of accompanyingCourse + */ const getAccompanyingCourse = (id) => { - const url = `/api/1.0/person/accompanying-course/${id}.json`; - return fetch(url) - .then(response => { - if (response.ok) { return response.json(); } - throw { msg: 'Error while retriving AccompanyingPeriod Course.', sta: response.status, txt: response.statusText, err: new Error(), body: response.body }; - }); + const url = `/api/1.0/person/accompanying-course/${id}.json`; + return fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } + throw { + msg: "Error while retriving AccompanyingPeriod Course.", + sta: response.status, + txt: response.statusText, + err: new Error(), + body: response.body, + }; + }); }; -const getUsers = () => fetchResults('/api/1.0/main/user.json'); +const getUsers = () => fetchResults("/api/1.0/main/user.json"); const getReferrersSuggested = (course) => { - const url = `/api/1.0/person/accompanying-course/${course.id}/referrers-suggested.json`; - return fetchResults(url); -} + const url = `/api/1.0/person/accompanying-course/${course.id}/referrers-suggested.json`; + return fetchResults(url); +}; -const getUserJobs = () => fetchResults('/api/1.0/main/user-job.json'); +const getUserJobs = () => fetchResults("/api/1.0/main/user-job.json"); const getSocialIssues = () => { - const url = `/api/1.0/person/social-work/social-issue.json`; - return fetch(url) - .then(response => { - if (response.ok) { return response.json(); } - throw { msg: 'Error while retriving Social Issues.', sta: response.status, txt: response.statusText, err: new Error(), body: response.body }; - }); + const url = `/api/1.0/person/social-work/social-issue.json`; + return fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } + throw { + msg: "Error while retriving Social Issues.", + sta: response.status, + txt: response.statusText, + err: new Error(), + body: response.body, + }; + }); }; const whoami = () => { - const url = `/api/1.0/main/whoami.json`; - return fetch(url) - .then(response => { - if (response.ok) { return response.json(); } - throw { msg: 'Error while getting whoami.', sta: response.status, txt: response.statusText, err: new Error(), body: response.body }; - }); + const url = `/api/1.0/main/whoami.json`; + return fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } + throw { + msg: "Error while getting whoami.", + sta: response.status, + txt: response.statusText, + err: new Error(), + body: response.body, + }; + }); }; export { - whoami, - getSocialIssues, - getAccompanyingCourse, - getUsers, - getReferrersSuggested, - getUserJobs + whoami, + getSocialIssues, + getAccompanyingCourse, + getUsers, + getReferrersSuggested, + getUserJobs, }; diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/AdminLocation.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/AdminLocation.vue index 57ca22345..a91cd1488 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/AdminLocation.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/AdminLocation.vue @@ -1,10 +1,10 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner.vue index 2dceb6ad4..dec68cd1f 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner.vue @@ -9,11 +9,15 @@ class="text-md-end d-md-block" > - {{ $t('course.step.draft') }} + {{ $t("course.step.draft") }} - {{ $t('course.step.active') }} + {{ $t("course.step.active") }} - {{ $t('course.step.inactive_short') }} + {{ $t("course.step.inactive_short") }} - {{ $t('course.step.inactive_long') }} + {{ $t("course.step.inactive_long") }} - {{ $t('course.open_at') }}{{ $d(accompanyingCourse.openingDate.datetime, 'text') }} + {{ $t("course.open_at") + }}{{ $d(accompanyingCourse.openingDate.datetime, "text") }} - - {{ $t('course.referrer') }}:  + + {{ $t("course.referrer") }}:  {{ accompanyingCourse.user.text }} - + - {{ $t('course.step.closed') }} + {{ $t("course.step.closed") }} - {{ $d(accompanyingCourse.openingDate.datetime, 'text') }} - {{ $d(accompanyingCourse.closingDate.datetime, 'text') }} + {{ $d(accompanyingCourse.openingDate.datetime, "text") }} - + {{ $d(accompanyingCourse.closingDate.datetime, "text") }} - - {{ $t('course.referrer') }}: {{ accompanyingCourse.user.text }} + + {{ $t("course.referrer") }}: + {{ accompanyingCourse.user.text }} @@ -95,35 +94,35 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner/PersonsAssociated.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner/PersonsAssociated.vue index 97599afe1..9a957b74e 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner/PersonsAssociated.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Banner/PersonsAssociated.vue @@ -1,23 +1,19 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Comment.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Comment.vue index e03515d63..d7c11d36d 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Comment.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/components/Comment.vue @@ -1,6 +1,6 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/index.js b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/index.js index a420671b5..9bb76883d 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/index.js +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/index.js @@ -1,59 +1,56 @@ -import { createApp } from 'vue' -import { _createI18n } from 'ChillMainAssets/vuejs/_js/i18n' -import { appMessages } from './js/i18n' -import { initPromise } from './store' -import 'vue-toast-notification/dist/theme-sugar.css'; -import App from './App.vue'; -import Banner from './components/Banner.vue'; +import { createApp } from "vue"; +import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n"; +import { appMessages } from "./js/i18n"; +import { initPromise } from "./store"; +import "vue-toast-notification/dist/theme-sugar.css"; +import App from "./App.vue"; +import Banner from "./components/Banner.vue"; import ToastPlugin from "vue-toast-notification"; const root = window.vueRootComponent; /* -* Load all App component, for AccompanyingCourse edition page -*/ -if (root === 'app') { - initPromise(root).then(store => { + * Load all App component, for AccompanyingCourse edition page + */ +if (root === "app") { + initPromise(root).then((store) => { + const i18n = _createI18n(appMessages); - const i18n = _createI18n(appMessages); - - const app = createApp({ - template: ``, - }) + const app = createApp({ + template: ``, + }) .use(store) .use(i18n) .use(ToastPlugin, { - position: "bottom-right", - type: "error", - duration: 5000, - dismissible: true + position: "bottom-right", + type: "error", + duration: 5000, + dismissible: true, }) - .component('app', App) - .mount('#accompanying-course') - }); + .component("app", App) + .mount("#accompanying-course"); + }); } /* -* Load only Banner sub-component, for all others AccompanyingCourse page -*/ -if (root === 'banner') { - initPromise(root).then(store => { + * Load only Banner sub-component, for all others AccompanyingCourse page + */ +if (root === "banner") { + initPromise(root).then((store) => { + const i18n = _createI18n(appMessages); - const i18n = _createI18n(appMessages); - - const app = createApp({ - template: ``, - }) + const app = createApp({ + template: ``, + }) .use(store) .use(i18n) .use(ToastPlugin, { - position: "bottom-right", - type: "error", - duration: 5000, - dismissible: true + position: "bottom-right", + type: "error", + duration: 5000, + dismissible: true, }) - .component('banner', Banner) - .mount('#banner-accompanying-course'); - }); - + .component("banner", Banner) + .mount("#banner-accompanying-course"); + }); } diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/js/i18n.js b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/js/i18n.js index 1a46a79ca..f564acfb3 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/js/i18n.js +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/js/i18n.js @@ -1,184 +1,217 @@ -import { personMessages } from 'ChillPersonAssets/vuejs/_js/i18n'; -import { thirdpartyMessages } from 'ChillThirdPartyAssets/vuejs/_js/i18n'; -import { addressMessages } from 'ChillMainAssets/vuejs/Address/i18n'; -import { ontheflyMessages } from 'ChillMainAssets/vuejs/OnTheFly/i18n'; +import { personMessages } from "ChillPersonAssets/vuejs/_js/i18n"; +import { thirdpartyMessages } from "ChillThirdPartyAssets/vuejs/_js/i18n"; +import { addressMessages } from "ChillMainAssets/vuejs/Address/i18n"; +import { ontheflyMessages } from "ChillMainAssets/vuejs/OnTheFly/i18n"; const appMessages = { - fr: { - course: { - id: "id", - title: { - draft: "Création d'un nouveau parcours", - active: "Modification du parcours" - }, - opening_date: "Date d'ouverture", - closing_date: "Date de clôture", - remark: "Commentaire", - closing_motive: "Motif de clôture", - user: "TMS", - flags: "Indicateurs", - status: "État", - step: { - draft: "Brouillon", - active: "En file active", - closed: "Cloturé", - inactive_short: "Hors file active", - inactive_long: "Pré-archivé", - }, - open_at: "ouvert le ", - by: "par ", - referrer: "Référent", - emergency: "urgent", - confidential: "confidentiel", - regular: "régulier", - occasional: "ponctuel", - absent: "Absent", + fr: { + course: { + id: "id", + title: { + draft: "Création d'un nouveau parcours", + active: "Modification du parcours", }, - origin: { - title: "Origine de la demande", - label: "Origine de la demande", - placeholder: "Renseignez l'origine de la demande", - not_valid: "Indiquez une origine à la demande", + opening_date: "Date d'ouverture", + closing_date: "Date de clôture", + remark: "Commentaire", + closing_motive: "Motif de clôture", + user: "TMS", + flags: "Indicateurs", + status: "État", + step: { + draft: "Brouillon", + active: "En file active", + closed: "Cloturé", + inactive_short: "Hors file active", + inactive_long: "Pré-archivé", }, - admin_location: { - title: "Localisation administrative", - label: "Localisation administrative", - placeholder: "Renseignez la localisation administrative", - not_valid: "Indiquez une localisation administrative", - }, - persons_associated: { - title: "Usagers concernés", - counter: "Il n'y a pas encore d'usagers | 1 usager | {count} usagers", - firstname: "Prénom", - lastname: "Nom", - name: "Nom", - startdate: "Date d'entrée", - enddate: "Date de sortie", - add_persons: "Ajouter des usagers", - date_start_to_end: "Participation du {start} au {end}", - leave_course: "L'usager quitte le parcours", - sure: "Êtes-vous sûr ?", - sure_description: "Une fois confirmé, il ne sera pas possible de faire marche arrière ! La sortie reste cependant consignée dans l'historique du parcours.", - ok: "Oui, l'usager quitte le parcours", - show_household_number: "Voir le ménage (n° {id})", - show_household: "Voir le ménage", - person_without_household_warning: "Certaines usagers n'appartiennent actuellement à aucun ménage. Veuillez les associer à un ménage dès que possible.", - update_household: "Associer à un ménage", - participation_not_valid: "Sélectionnez ou créez au minimum 1 usager", - }, - requestor: { - title: "Demandeur", - add_requestor: "Ajouter un demandeur", - is_anonymous: "Le demandeur est anonyme", - counter: "Il n'y a pas encore de demandeur", - type: "Type", - person_id: "id", - text: "Dénomination", - firstName: "Prénom", - lastName: "Nom", - birthdate: "Date de naissance", - center: "Centre", - phonenumber: "Téléphone", - mobilenumber: "Mobile", - altNames: "Autres noms", - address: "Adresse", - location: "Localité", - }, - social_issue: { - title: "Problématiques sociales", - label: "Choisir les problématiques sociales", - not_valid: "Sélectionnez au minimum une problématique sociale", - }, - courselocation: { - title: "Localisation du parcours", - add_temporary_address: "Ajouter une adresse temporaire", - edit_temporary_address: "Modifier l'adresse temporaire", - assign_course_address: "Désigner comme l'adresse du parcours", - remove_button: "Enlever l'adresse", - temporary_address_must_be_changed: "Cette adresse est temporaire. Le parcours devrait être localisé auprès d'un usager concerné.", - associate_at_least_one_person_with_one_household_with_address: "Commencez d'abord par associer un membre du parcours à un ménage, et indiquez une adresse à ce ménage.", - sure: "Êtes-vous sûr ?", - sure_description: "Voulez-vous faire de cette adresse l'adresse du parcours ?", - ok: "Désigner comme adresse du parcours", - person_locator: "Parcours localisé auprès de {0}", - not_valid: "Indiquez au minimum une localisation temporaire du parcours", - no_address: "Il n'y a pas d'adresse associée au parcours" - }, - scopes: { - title: "Services concernés", - add_at_least_one: "Indiquez au moins un service", - }, - referrer: { - title: "Référent du parcours", - label: "Vous pouvez choisir un TMS ou vous assigner directement comme référent", - placeholder: "Choisir un TMS", - assign_me: "M'assigner comme référent", - }, - resources: { - title: "Interlocuteurs privilégiés", - counter: "Il n'y a pas encore d'interlocuteur | 1 interlocuteur | {count} interlocuteurs", - text: "Dénomination", - description: "Description", - add_resources: "Ajouter des interlocuteurs", - }, - comment: { - title: "Observations", - label: "Ajout d'une note", - content: "Rédigez une première note…", - created_by: "créé par {0}, mis à jour le {1}" - }, - confirm: { - title: "Confirmation", - text_draft: "Le parcours est actuellement à l'état de {0}.", - text_active: "En validant cette étape, vous lui donnez le statut {0}.", - alert_validation: "Certaines conditions ne sont pas remplies pour pouvoir confirmer le parcours :", - participation_not_valid: "sélectionnez au minimum 1 usager", - socialIssue_not_valid: "sélectionnez au minimum une problématique sociale", - location_not_valid: "indiquez au minimum une localisation temporaire du parcours", - origin_not_valid: "Indiquez une origine à la demande", - adminLocation_not_valid: "Indiquez une localisation administrative à la demande", - job_not_valid: "Indiquez un métier du référent", - set_a_scope: "indiquez au moins un service", - sure: "Êtes-vous sûr ?", - sure_description: "Une fois le changement confirmé, il ne sera plus possible de le remettre à l'état de brouillon !", - sure_referrer: "Êtes-vous sûr de vouloir assigner ce parcours à {referrer}", - ok: "Confirmer le parcours", - delete: "Supprimer le parcours", - ok_referrer: "Confirmer le référent", - no_suggested_referrer: "Il n'y a aucun référent qui puisse être suggéré pour ce parcours. Vérifiez la localisation du parcours, les métiers et service indiqués. Si les données sont correctes, vous pouvez confirmer ce parcours.", - one_suggested_referrer: "Un unique référent peut être suggéré pour ce parcours", - choose_suggested_referrer: "Voulez-vous le désigner directement ?", - choose_button: "Désigner", - do_not_choose_button: "Ne pas désigner" - }, - job: { - label: "Métier", - placeholder: "Choisir un métier", - not_valid: "Sélectionnez un métier du référent" - }, - startdate: { - change: "Date d'ouverture", - // update: "La nouvelle date d'ouverture a été enregistrée" - }, - // catch errors - 'Error while updating AccompanyingPeriod Course.': "Erreur du serveur lors de la mise à jour du parcours d'accompagnement.", - 'Error while retriving AccompanyingPeriod Course.': "Erreur du serveur lors du chargement du parcours d'accompagnement.", - 'Error while confirming AccompanyingPeriod Course.': "Erreur du serveur lors de la confirmation du parcours d'accompagnement.", - 'Error while retriving Social Issues.': "Erreur du serveur lors du chargement des problématique sociales.", - 'Error while sending AccompanyingPeriod Course participation.': "Erreur du serveur lors de l'envoi des infos d'un usager.", - 'Error while sending AccompanyingPeriod Course requestor': "Erreur du serveur lors de l'envoi des infos du demandeur.", - 'Error while sending AccompanyingPeriod Course resource.': "Erreur du serveur lors de l'envoi des infos d'un interlocuteur privilégié.", - 'Error while updating SocialIssue.': "Erreur du serveur lors de la mise à jour d'une problématique sociale.", - 'Error while retriving users.': "Erreur du serveur lors du chargement de la liste des travailleurs.", - 'Error while getting whoami.': "Erreur du serveur lors de la requête 'qui suis-je ?'", - 'Error while retriving origin\'s list.': "Erreur du serveur lors du chargement de la liste des origines de la demande.", - 'Only the referrer can toggle the intensity of an accompanying course': "Seul le référent peut modifier l'intensité d'un parcours.", - 'Only the referrer can toggle the confidentiality of an accompanying course': "Seul le référent peut modifier la confidentialité d'un parcours." - } + open_at: "ouvert le ", + by: "par ", + referrer: "Référent", + emergency: "urgent", + confidential: "confidentiel", + regular: "régulier", + occasional: "ponctuel", + absent: "Absent", + }, + origin: { + title: "Origine de la demande", + label: "Origine de la demande", + placeholder: "Renseignez l'origine de la demande", + not_valid: "Indiquez une origine à la demande", + }, + admin_location: { + title: "Localisation administrative", + label: "Localisation administrative", + placeholder: "Renseignez la localisation administrative", + not_valid: "Indiquez une localisation administrative", + }, + persons_associated: { + title: "Usagers concernés", + counter: "Il n'y a pas encore d'usagers | 1 usager | {count} usagers", + firstname: "Prénom", + lastname: "Nom", + name: "Nom", + startdate: "Date d'entrée", + enddate: "Date de sortie", + add_persons: "Ajouter des usagers", + date_start_to_end: "Participation du {start} au {end}", + leave_course: "L'usager quitte le parcours", + sure: "Êtes-vous sûr ?", + sure_description: + "Une fois confirmé, il ne sera pas possible de faire marche arrière ! La sortie reste cependant consignée dans l'historique du parcours.", + ok: "Oui, l'usager quitte le parcours", + show_household_number: "Voir le ménage (n° {id})", + show_household: "Voir le ménage", + person_without_household_warning: + "Certaines usagers n'appartiennent actuellement à aucun ménage. Veuillez les associer à un ménage dès que possible.", + update_household: "Associer à un ménage", + participation_not_valid: "Sélectionnez ou créez au minimum 1 usager", + }, + requestor: { + title: "Demandeur", + add_requestor: "Ajouter un demandeur", + is_anonymous: "Le demandeur est anonyme", + counter: "Il n'y a pas encore de demandeur", + type: "Type", + person_id: "id", + text: "Dénomination", + firstName: "Prénom", + lastName: "Nom", + birthdate: "Date de naissance", + center: "Centre", + phonenumber: "Téléphone", + mobilenumber: "Mobile", + altNames: "Autres noms", + address: "Adresse", + location: "Localité", + }, + social_issue: { + title: "Problématiques sociales", + label: "Choisir les problématiques sociales", + not_valid: "Sélectionnez au minimum une problématique sociale", + }, + courselocation: { + title: "Localisation du parcours", + add_temporary_address: "Ajouter une adresse temporaire", + edit_temporary_address: "Modifier l'adresse temporaire", + assign_course_address: "Désigner comme l'adresse du parcours", + remove_button: "Enlever l'adresse", + temporary_address_must_be_changed: + "Cette adresse est temporaire. Le parcours devrait être localisé auprès d'un usager concerné.", + associate_at_least_one_person_with_one_household_with_address: + "Commencez d'abord par associer un membre du parcours à un ménage, et indiquez une adresse à ce ménage.", + sure: "Êtes-vous sûr ?", + sure_description: + "Voulez-vous faire de cette adresse l'adresse du parcours ?", + ok: "Désigner comme adresse du parcours", + person_locator: "Parcours localisé auprès de {0}", + not_valid: "Indiquez au minimum une localisation temporaire du parcours", + no_address: "Il n'y a pas d'adresse associée au parcours", + }, + scopes: { + title: "Services concernés", + add_at_least_one: "Indiquez au moins un service", + }, + referrer: { + title: "Référent du parcours", + label: + "Vous pouvez choisir un TMS ou vous assigner directement comme référent", + placeholder: "Choisir un TMS", + assign_me: "M'assigner comme référent", + }, + resources: { + title: "Interlocuteurs privilégiés", + counter: + "Il n'y a pas encore d'interlocuteur | 1 interlocuteur | {count} interlocuteurs", + text: "Dénomination", + description: "Description", + add_resources: "Ajouter des interlocuteurs", + }, + comment: { + title: "Observations", + label: "Ajout d'une note", + content: "Rédigez une première note…", + created_by: "créé par {0}, mis à jour le {1}", + }, + confirm: { + title: "Confirmation", + text_draft: "Le parcours est actuellement à l'état de {0}.", + text_active: + "En validant cette étape, vous lui donnez le statut {0}.", + alert_validation: + "Certaines conditions ne sont pas remplies pour pouvoir confirmer le parcours :", + participation_not_valid: "sélectionnez au minimum 1 usager", + socialIssue_not_valid: + "sélectionnez au minimum une problématique sociale", + location_not_valid: + "indiquez au minimum une localisation temporaire du parcours", + origin_not_valid: "Indiquez une origine à la demande", + adminLocation_not_valid: + "Indiquez une localisation administrative à la demande", + job_not_valid: "Indiquez un métier du référent", + set_a_scope: "indiquez au moins un service", + sure: "Êtes-vous sûr ?", + sure_description: + "Une fois le changement confirmé, il ne sera plus possible de le remettre à l'état de brouillon !", + sure_referrer: + "Êtes-vous sûr de vouloir assigner ce parcours à {referrer}", + ok: "Confirmer le parcours", + delete: "Supprimer le parcours", + ok_referrer: "Confirmer le référent", + no_suggested_referrer: + "Il n'y a aucun référent qui puisse être suggéré pour ce parcours. Vérifiez la localisation du parcours, les métiers et service indiqués. Si les données sont correctes, vous pouvez confirmer ce parcours.", + one_suggested_referrer: + "Un unique référent peut être suggéré pour ce parcours", + choose_suggested_referrer: "Voulez-vous le désigner directement ?", + choose_button: "Désigner", + do_not_choose_button: "Ne pas désigner", + }, + job: { + label: "Métier", + placeholder: "Choisir un métier", + not_valid: "Sélectionnez un métier du référent", + }, + startdate: { + change: "Date d'ouverture", + // update: "La nouvelle date d'ouverture a été enregistrée" + }, + // catch errors + "Error while updating AccompanyingPeriod Course.": + "Erreur du serveur lors de la mise à jour du parcours d'accompagnement.", + "Error while retriving AccompanyingPeriod Course.": + "Erreur du serveur lors du chargement du parcours d'accompagnement.", + "Error while confirming AccompanyingPeriod Course.": + "Erreur du serveur lors de la confirmation du parcours d'accompagnement.", + "Error while retriving Social Issues.": + "Erreur du serveur lors du chargement des problématique sociales.", + "Error while sending AccompanyingPeriod Course participation.": + "Erreur du serveur lors de l'envoi des infos d'un usager.", + "Error while sending AccompanyingPeriod Course requestor": + "Erreur du serveur lors de l'envoi des infos du demandeur.", + "Error while sending AccompanyingPeriod Course resource.": + "Erreur du serveur lors de l'envoi des infos d'un interlocuteur privilégié.", + "Error while updating SocialIssue.": + "Erreur du serveur lors de la mise à jour d'une problématique sociale.", + "Error while retriving users.": + "Erreur du serveur lors du chargement de la liste des travailleurs.", + "Error while getting whoami.": + "Erreur du serveur lors de la requête 'qui suis-je ?'", + "Error while retriving origin's list.": + "Erreur du serveur lors du chargement de la liste des origines de la demande.", + "Only the referrer can toggle the intensity of an accompanying course": + "Seul le référent peut modifier l'intensité d'un parcours.", + "Only the referrer can toggle the confidentiality of an accompanying course": + "Seul le référent peut modifier la confidentialité d'un parcours.", + }, }; -Object.assign(appMessages.fr, personMessages.fr, thirdpartyMessages.fr, addressMessages.fr, ontheflyMessages.fr); +Object.assign( + appMessages.fr, + personMessages.fr, + thirdpartyMessages.fr, + addressMessages.fr, + ontheflyMessages.fr, +); -export { - appMessages -}; +export { appMessages }; diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/store/index.js b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/store/index.js index 97a48d387..6e2fc51b1 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/store/index.js +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourse/store/index.js @@ -1,41 +1,37 @@ -import 'es6-promise/auto'; -import { createStore } from 'vuex'; -import { fetchScopes } from 'ChillMainAssets/lib/api/apiMethods.ts'; -import { getAccompanyingCourse, - getReferrersSuggested, - getUsers, -} from '../api'; -import { makeFetch } from 'ChillMainAssets/lib/api/apiMethods'; -import { datetimeToISO, ISOToDate } from 'ChillMainAssets/chill/js/date'; +import "es6-promise/auto"; +import { createStore } from "vuex"; +import { fetchScopes } from "ChillMainAssets/lib/api/apiMethods.ts"; +import { getAccompanyingCourse, getReferrersSuggested, getUsers } from "../api"; +import { makeFetch } from "ChillMainAssets/lib/api/apiMethods"; +import { datetimeToISO, ISOToDate } from "ChillMainAssets/chill/js/date"; - -const debug = process.env.NODE_ENV !== 'production'; +const debug = process.env.NODE_ENV !== "production"; const id = window.accompanyingCourseId; let getScopesPromise = (root) => { - if (root === 'app') { - return fetchScopes(); - } -} + if (root === "app") { + return fetchScopes(); + } +}; let accompanyingCoursePromise = getAccompanyingCourse(id); -let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCoursePromise]) - .then(([scopes, accompanyingCourse]) => new Promise((resolve) => { - - const store = createStore({ - strict: debug, - modules: { - }, - state: { +let initPromise = (root) => + Promise.all([getScopesPromise(root), accompanyingCoursePromise]).then( + ([scopes, accompanyingCourse]) => + new Promise((resolve) => { + const store = createStore({ + strict: debug, + modules: {}, + state: { accompanyingCourse: accompanyingCourse, addressContext: {}, errorMsg: [], // all the available scopes scopes: scopes, // the scopes at start. If the user remove all scopes, we re-add those scopes, by security - scopesAtStart: accompanyingCourse.scopes.map(scope => scope), + scopesAtStart: accompanyingCourse.scopes.map((scope) => scope), // the scope states at server side - scopesAtBackend: accompanyingCourse.scopes.map(scope => scope), + scopesAtBackend: accompanyingCourse.scopes.map((scope) => scope), // the users which are available for referrer referrersSuggested: [], // all the users available @@ -45,346 +41,404 @@ let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCou updateCommentAbortController: null, // waiting response for inserting first comment postFirstPinnedCommentResponse: null, - }, - getters: { + }, + getters: { isPersonLocatingCourse: (state) => (person) => { - if (state.accompanyingCourse.locationStatus !== 'person') { - return false; - } + if (state.accompanyingCourse.locationStatus !== "person") { + return false; + } - return state.accompanyingCourse.personLocation.id === person.id; + return state.accompanyingCourse.personLocation.id === person.id; }, isParticipationValid(state) { - return state.accompanyingCourse.participations.length > 0; + return state.accompanyingCourse.participations.length > 0; }, isSocialIssueValid(state) { - return state.accompanyingCourse.socialIssues.length > 0; + return state.accompanyingCourse.socialIssues.length > 0; }, isOriginValid(state) { - return state.accompanyingCourse.origin !== null; + return state.accompanyingCourse.origin !== null; }, isAdminLocationValid(state) { - return state.accompanyingCourse.administrativeLocation !== null; + return state.accompanyingCourse.administrativeLocation !== null; }, isLocationValid(state) { - return state.accompanyingCourse.location !== null; + return state.accompanyingCourse.location !== null; }, isJobValid(state) { - return state.accompanyingCourse.job !== null; + return state.accompanyingCourse.job !== null; }, isScopeValid(state) { - //console.log('is scope valid', state.accompanyingCourse.scopes.length > 0); - return state.accompanyingCourse.scopes.length > 0; + //console.log('is scope valid', state.accompanyingCourse.scopes.length > 0); + return state.accompanyingCourse.scopes.length > 0; }, validationKeys(state, getters) { - let keys = []; - if (!getters.isParticipationValid) { keys.push('participation'); } - if (!getters.isLocationValid) { keys.push('location'); } - if (!getters.isJobValid) { keys.push('job'); } - if (!getters.isSocialIssueValid) { keys.push('socialIssue'); } - if (!getters.isOriginValid) { keys.push('origin'); } - if (!getters.isAdminLocationValid) { keys.push('adminLocation'); } - if (!getters.isScopeValid) { keys.push('scopes'); } - //console.log('getter keys', keys); - return keys; + let keys = []; + if (!getters.isParticipationValid) { + keys.push("participation"); + } + if (!getters.isLocationValid) { + keys.push("location"); + } + if (!getters.isJobValid) { + keys.push("job"); + } + if (!getters.isSocialIssueValid) { + keys.push("socialIssue"); + } + if (!getters.isOriginValid) { + keys.push("origin"); + } + if (!getters.isAdminLocationValid) { + keys.push("adminLocation"); + } + if (!getters.isScopeValid) { + keys.push("scopes"); + } + //console.log('getter keys', keys); + return keys; }, isValidToBeConfirmed(state, getters) { - if (getters.validationKeys.length === 0) { - return true; - } - return false; + if (getters.validationKeys.length === 0) { + return true; + } + return false; }, canTogglePermission(state) { - if (state.permissions.roles) { - return state.permissions.roles['CHILL_PERSON_ACCOMPANYING_PERIOD_TOGGLE_CONFIDENTIAL']; - } + if (state.permissions.roles) { + return state.permissions.roles[ + "CHILL_PERSON_ACCOMPANYING_PERIOD_TOGGLE_CONFIDENTIAL" + ]; + } - return false; + return false; }, usersFilteredByJob(state) { - return state.users.filter(u => { - if (null !== state.accompanyingCourse.job) { - return (u.user_job === null ? null : u.user_job.id) === state.accompanyingCourse.job.id; - } else { - return true; - } - }); + return state.users.filter((u) => { + if (null !== state.accompanyingCourse.job) { + return ( + (u.user_job === null ? null : u.user_job.id) === + state.accompanyingCourse.job.id + ); + } else { + return true; + } + }); }, usersSuggestedFilteredByJob(state) { - return state.referrersSuggested.filter(u => { + return state.referrersSuggested + .filter((u) => { if (null !== state.accompanyingCourse.job) { - return (u.user_job === null ? null : u.user_job.id) === state.accompanyingCourse.job.id; + return ( + (u.user_job === null ? null : u.user_job.id) === + state.accompanyingCourse.job.id + ); } else { - return true; + return true; } - }).filter(u => { + }) + .filter((u) => { if (null !== state.accompanyingCourse.user) { - return u.id !== state.accompanyingCourse.user.id; + return u.id !== state.accompanyingCourse.user.id; } return true; - }); + }); }, - }, - mutations: { + }, + mutations: { catchError(state, error) { - // console.log('### mutation: a new error have been catched and pushed in store !', error); - state.errorMsg.push(error); + // console.log('### mutation: a new error have been catched and pushed in store !', error); + state.errorMsg.push(error); }, removeParticipation(state, participation) { - //console.log('### mutation: remove participation', participation.id); - state.accompanyingCourse.participations = state.accompanyingCourse.participations.filter(element => element !== participation); + //console.log('### mutation: remove participation', participation.id); + state.accompanyingCourse.participations = + state.accompanyingCourse.participations.filter( + (element) => element !== participation, + ); }, closeParticipation(state, { response, payload }) { - //console.log('### mutation: close item', { participation, payload }); - // find row position and replace by closed participation - state.accompanyingCourse.participations.splice( - state.accompanyingCourse.participations.findIndex(element => element === payload), 1, response - ); + //console.log('### mutation: close item', { participation, payload }); + // find row position and replace by closed participation + state.accompanyingCourse.participations.splice( + state.accompanyingCourse.participations.findIndex( + (element) => element === payload, + ), + 1, + response, + ); }, addParticipation(state, participation) { - //console.log('### mutation: add participation', participation); - state.accompanyingCourse.participations.push(participation); + //console.log('### mutation: add participation', participation); + state.accompanyingCourse.participations.push(participation); }, removeRequestor(state) { - //console.log('### mutation: removeRequestor'); - state.accompanyingCourse.requestor = null; + //console.log('### mutation: removeRequestor'); + state.accompanyingCourse.requestor = null; }, addRequestor(state, requestor) { - //console.log('### mutation: addRequestor', requestor); - state.accompanyingCourse.requestor = requestor; + //console.log('### mutation: addRequestor', requestor); + state.accompanyingCourse.requestor = requestor; }, requestorIsAnonymous(state, value) { - //console.log('### mutation: requestorIsAnonymous', value); - state.accompanyingCourse.requestorAnonymous = value; + //console.log('### mutation: requestorIsAnonymous', value); + state.accompanyingCourse.requestorAnonymous = value; }, removeResource(state, resource) { - //console.log('### mutation: removeResource', resource); - state.accompanyingCourse.resources = state.accompanyingCourse.resources.filter(element => element !== resource); + //console.log('### mutation: removeResource', resource); + state.accompanyingCourse.resources = + state.accompanyingCourse.resources.filter( + (element) => element !== resource, + ); }, addResource(state, resource) { - //console.log('### mutation: addResource', resource); - state.accompanyingCourse.resources.push(resource); + //console.log('### mutation: addResource', resource); + state.accompanyingCourse.resources.push(resource); }, updateResource(state, payload) { - console.log('### mutation: updateResource', payload); - let i = state.accompanyingCourse.resources.findIndex(r => r.id === payload.id); - state.accompanyingCourse.resources[i] = payload; + console.log("### mutation: updateResource", payload); + let i = state.accompanyingCourse.resources.findIndex( + (r) => r.id === payload.id, + ); + state.accompanyingCourse.resources[i] = payload; }, updatePerson(state, payload) { - console.log('### mutation: updatePerson', payload); - let i = null; - switch (payload.target) { - case 'participation': - i = state.accompanyingCourse.participations.findIndex(e => e.person.id === payload.person.id ); - state.accompanyingCourse.participations[i].person = payload.person; - break; - case 'requestor': - state.accompanyingCourse.requestor = payload.person; - break; - case 'resource': - i = state.accompanyingCourse.resources.findIndex(e => e.resource.id === payload.person.id ); - state.accompanyingCourse.resources[i].resource = payload.person; - break; - } + console.log("### mutation: updatePerson", payload); + let i = null; + switch (payload.target) { + case "participation": + i = state.accompanyingCourse.participations.findIndex( + (e) => e.person.id === payload.person.id, + ); + state.accompanyingCourse.participations[i].person = + payload.person; + break; + case "requestor": + state.accompanyingCourse.requestor = payload.person; + break; + case "resource": + i = state.accompanyingCourse.resources.findIndex( + (e) => e.resource.id === payload.person.id, + ); + state.accompanyingCourse.resources[i].resource = + payload.person; + break; + } }, updateThirdparty(state, payload) { - console.log('### mutation: updateThirdparty', payload); - let i = null; - switch (payload.target) { - case 'requestor': - state.accompanyingCourse.requestor = payload.thirdparty; - break; - case 'resource': - i = state.accompanyingCourse.resources.findIndex(e => e.resource.id === payload.thirdparty.id ); - state.accompanyingCourse.resources[i].resource = payload.thirdparty; - break; - } + console.log("### mutation: updateThirdparty", payload); + let i = null; + switch (payload.target) { + case "requestor": + state.accompanyingCourse.requestor = payload.thirdparty; + break; + case "resource": + i = state.accompanyingCourse.resources.findIndex( + (e) => e.resource.id === payload.thirdparty.id, + ); + state.accompanyingCourse.resources[i].resource = + payload.thirdparty; + break; + } }, toggleIntensity(state, value) { - state.accompanyingCourse.intensity = value; + state.accompanyingCourse.intensity = value; }, toggleEmergency(state, value) { - //console.log('### mutation: toggleEmergency'); - state.accompanyingCourse.emergency = value; + //console.log('### mutation: toggleEmergency'); + state.accompanyingCourse.emergency = value; }, toggleConfidential(state, value) { - //console.log('### mutation: toggleConfidential'); - state.accompanyingCourse.confidential = value; + //console.log('### mutation: toggleConfidential'); + state.accompanyingCourse.confidential = value; }, setPinnedComment(state, content) { - if (null === state.accompanyingCourse.pinnedComment) { - state.accompanyingCourse.pinnedComment = { - id: -1, - content, - type: "accompanying_period_comment", - }; - } else { - state.accompanyingCourse.pinnedComment.content = content; - } + if (null === state.accompanyingCourse.pinnedComment) { + state.accompanyingCourse.pinnedComment = { + id: -1, + content, + type: "accompanying_period_comment", + }; + } else { + state.accompanyingCourse.pinnedComment.content = content; + } }, setPinnedCommentDetails(state, value) { - state.accompanyingCourse.pinnedComment.id = value.id; - if (typeof value.creator !== 'undefined') { - state.accompanyingCourse.pinnedComment.creator = value.creator; - state.accompanyingCourse.pinnedComment.updatedBy = value.updatedBy; - state.accompanyingCourse.pinnedComment.updatedAt = value.updatedAt; - state.accompanyingCourse.pinnedComment.createdAt = value.createdAt; - - } + state.accompanyingCourse.pinnedComment.id = value.id; + if (typeof value.creator !== "undefined") { + state.accompanyingCourse.pinnedComment.creator = value.creator; + state.accompanyingCourse.pinnedComment.updatedBy = + value.updatedBy; + state.accompanyingCourse.pinnedComment.updatedAt = + value.updatedAt; + state.accompanyingCourse.pinnedComment.createdAt = + value.createdAt; + } }, removePinnedComment(state) { - state.accompanyingCourse.pinnedComment = null; + state.accompanyingCourse.pinnedComment = null; }, setPinCommentAbortController(state, value) { - state.updateCommentAbortController = value; + state.updateCommentAbortController = value; }, setPostFirstPinnedCommentResponse(state, value) { - state.postFirstPinnedCommentResponse = value; + state.postFirstPinnedCommentResponse = value; }, updateSocialIssues(state, value) { - console.log('updateSocialIssues', value); - state.accompanyingCourse.socialIssues = value; + console.log("updateSocialIssues", value); + state.accompanyingCourse.socialIssues = value; }, refreshSocialIssues(state, issues) { - console.log('refreshSocialIssues', issues); - state.accompanyingCourse.socialIssues = issues; + console.log("refreshSocialIssues", issues); + state.accompanyingCourse.socialIssues = issues; }, updateOrigin(state, value) { - //console.log('value', value); - state.accompanyingCourse.origin = value; + //console.log('value', value); + state.accompanyingCourse.origin = value; }, updateAdminLocation(state, value) { - state.accompanyingCourse.administrativeLocation = value; + state.accompanyingCourse.administrativeLocation = value; }, updateReferrer(state, value) { - state.accompanyingCourse.user = value; + state.accompanyingCourse.user = value; }, updateJob(state, value) { - state.accompanyingCourse.job = value; + state.accompanyingCourse.job = value; }, setReferrersSuggested(state, users) { - state.referrersSuggested = users.map(u => { - if (state.accompanyingCourse.user !== null) { - if (state.accompanyingCourse.user.id === u.id) { - return state.accompanyingCourse.user; - } + state.referrersSuggested = users.map((u) => { + if (state.accompanyingCourse.user !== null) { + if (state.accompanyingCourse.user.id === u.id) { + return state.accompanyingCourse.user; } - return u; - }); + } + return u; + }); }, confirmAccompanyingCourse(state, response) { - //console.log('### mutation: confirmAccompanyingCourse: response', response); - state.accompanyingCourse.step = response.step; + //console.log('### mutation: confirmAccompanyingCourse: response', response); + state.accompanyingCourse.step = response.step; }, setAddressContext(state, context) { - //console.log('define location context'); - state.addressContext = context; + //console.log('define location context'); + state.addressContext = context; }, setUsers(state, users) { - state.users = users.map(u => { - if (state.accompanyingCourse.user !== null) { - if (state.accompanyingCourse.user.id === u.id) { - return state.accompanyingCourse.user; - } + state.users = users.map((u) => { + if (state.accompanyingCourse.user !== null) { + if (state.accompanyingCourse.user.id === u.id) { + return state.accompanyingCourse.user; } - return u; - }); + } + return u; + }); }, setPermissions(state, permissions) { - state.permissions = permissions; - // console.log('permissions', state.permissions); + state.permissions = permissions; + // console.log('permissions', state.permissions); }, updateLocation(state, r) { - //console.log('### mutation: set location attributes', r); - state.accompanyingCourse.locationStatus = r.locationStatus; - if (r.locationStatus !== 'person') { - state.addressContext.addressId = r.location.address_id; - //console.log('mutation: update context addressId', state.addressContext.addressId); - } - state.accompanyingCourse.location = r.location; - state.accompanyingCourse.personLocation = r.personLocation; + //console.log('### mutation: set location attributes', r); + state.accompanyingCourse.locationStatus = r.locationStatus; + if (r.locationStatus !== "person") { + state.addressContext.addressId = r.location.address_id; + //console.log('mutation: update context addressId', state.addressContext.addressId); + } + state.accompanyingCourse.location = r.location; + state.accompanyingCourse.personLocation = r.personLocation; }, setEditContextTrue(state, payload) { - //console.log('### mutation: set edit context true with addressId', payload.addressId); - state.addressContext.edit = true; - state.addressContext.addressId = payload.addressId; + //console.log('### mutation: set edit context true with addressId', payload.addressId); + state.addressContext.edit = true; + state.addressContext.addressId = payload.addressId; }, setScopes(state, scopes) { - state.accompanyingCourse.scopes = scopes; + state.accompanyingCourse.scopes = scopes; }, addScopeAtBackend(state, scope) { - let scopeIds = state.scopesAtBackend.map(s => s.id); - if (!scopeIds.includes(scope.id)) { - state.scopesAtBackend.push(scope); - } + let scopeIds = state.scopesAtBackend.map((s) => s.id); + if (!scopeIds.includes(scope.id)) { + state.scopesAtBackend.push(scope); + } }, - removeScopeAtBackend(state, scope){ - let scopeIds = state.scopesAtBackend.map(s => s.id); - if (scopeIds.includes(scope.id)) { - state.scopesAtBackend = state.scopesAtBackend.filter(s => s.id !== scope.id); - } + removeScopeAtBackend(state, scope) { + let scopeIds = state.scopesAtBackend.map((s) => s.id); + if (scopeIds.includes(scope.id)) { + state.scopesAtBackend = state.scopesAtBackend.filter( + (s) => s.id !== scope.id, + ); + } }, updateStartDate(state, date) { - state.accompanyingCourse.openingDate = date; - } - }, - actions: { + state.accompanyingCourse.openingDate = date; + }, + }, + actions: { //QUESTION: does this serve a purpose? Participations can be closed... removeParticipation({ commit }, payload) { - commit('removeParticipation', payload); - // fetch DELETE request... + commit("removeParticipation", payload); + // fetch DELETE request... }, addPerson({ commit }, payload) { - commit('updatePerson', { target: payload.target, person: payload.body }); + commit("updatePerson", { + target: payload.target, + person: payload.body, + }); }, addThirdparty({ commit }, payload) { - commit('updateThirdparty', { target: payload.target, thirdparty: payload.body }); + commit("updateThirdparty", { + target: payload.target, + thirdparty: payload.body, + }); }, /** * Add/close participation */ closeParticipation({ commit }, payload) { - const body = { type: payload.person.type, id: payload.person.id }; - const url = `/api/1.0/person/accompanying-course/${id}/participation.json`; + const body = { type: payload.person.type, id: payload.person.id }; + const url = `/api/1.0/person/accompanying-course/${id}/participation.json`; - return makeFetch('DELETE', url, body) - .then((response) => { - commit('closeParticipation', { response, payload }); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("DELETE", url, body) + .then((response) => { + commit("closeParticipation", { response, payload }); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, addParticipation({ commit }, payload) { - const body = { type: payload.result.type, id: payload.result.id }; - const url = `/api/1.0/person/accompanying-course/${id}/participation.json`; + const body = { type: payload.result.type, id: payload.result.id }; + const url = `/api/1.0/person/accompanying-course/${id}/participation.json`; - return makeFetch('POST', url, body) - .then((response) => { - commit('addParticipation', response); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("POST", url, body) + .then((response) => { + commit("addParticipation", response); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, /** * Add/remove pinnedComment */ removePinnedComment({ commit }, payload) { - const body = {type: "accompanying_period_comment", id: payload.id}; - const url = `/api/1.0/person/accompanying-course/${id}/comment.json`; + const body = { + type: "accompanying_period_comment", + id: payload.id, + }; + const url = `/api/1.0/person/accompanying-course/${id}/comment.json`; - return makeFetch('DELETE', url, body) - .then(() => { - commit('removePinnedComment'); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("DELETE", url, body) + .then(() => { + commit("removePinnedComment"); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, /** * internal method to insert a new comment @@ -395,30 +449,39 @@ let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCou * @returns {*} */ addPinnedComment({ commit, dispatch }, content) { - const url = `/api/1.0/person/accompanying-course/${id}/comment.json`; + const url = `/api/1.0/person/accompanying-course/${id}/comment.json`; - return makeFetch('POST', url, {type: "accompanying_period_comment", content}) - .then((response) => { - commit('setPinnedCommentDetails', response); - return dispatch('patchFirstComment', response); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("POST", url, { + type: "accompanying_period_comment", + content, + }) + .then((response) => { + commit("setPinnedCommentDetails", response); + return dispatch("patchFirstComment", response); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, updatePinnedComment({ commit, state, dispatch }, content) { - commit('setPinnedComment', content); - if (state.accompanyingCourse.pinnedComment.id === -1 && state.postFirstPinnedCommentResponse === null) { - let r = dispatch('addPinnedComment', content).then(() => { - commit('setPostFirstPinnedCommentResponse', null); - }); - commit('setPostFirstPinnedCommentResponse', r); - } else { - (state.postFirstPinnedCommentResponse === null ? Promise.resolve() : state.postFirstPinnedCommentResponse).then(() => { - dispatch('updateExistingPinnedComment', content); - }); - } + commit("setPinnedComment", content); + if ( + state.accompanyingCourse.pinnedComment.id === -1 && + state.postFirstPinnedCommentResponse === null + ) { + let r = dispatch("addPinnedComment", content).then(() => { + commit("setPostFirstPinnedCommentResponse", null); + }); + commit("setPostFirstPinnedCommentResponse", r); + } else { + (state.postFirstPinnedCommentResponse === null + ? Promise.resolve() + : state.postFirstPinnedCommentResponse + ).then(() => { + dispatch("updateExistingPinnedComment", content); + }); + } }, /** * internal method to patch an existing comment @@ -429,165 +492,181 @@ let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCou * @returns {*} */ updateExistingPinnedComment({ commit, state }, content) { - const payload = {type: "accompanying_period_comment", content, id: state.accompanyingCourse.pinnedComment.id}; - const url = `/api/1.0/person/accompanying-period/comment/${payload.id}.json`; + const payload = { + type: "accompanying_period_comment", + content, + id: state.accompanyingCourse.pinnedComment.id, + }; + const url = `/api/1.0/person/accompanying-period/comment/${payload.id}.json`; - if (state.updateCommentAbortController !== null) { - state.updateCommentAbortController.abort(); - commit('setPinCommentAbortController', null); - } + if (state.updateCommentAbortController !== null) { + state.updateCommentAbortController.abort(); + commit("setPinCommentAbortController", null); + } - let controller = new AbortController(); - commit('setPinCommentAbortController', controller); + let controller = new AbortController(); + commit("setPinCommentAbortController", controller); - return makeFetch('PATCH', url, payload, { signal: controller.signal }) - .then((response) => { - commit('setPinCommentAbortController', null); - commit('setPinnedCommentDetails', response); - }) - .catch((error) => { - commit('catchError', error); - commit('setPinCommentAbortController', null); - throw error; - }) + return makeFetch("PATCH", url, payload, { + signal: controller.signal, + }) + .then((response) => { + commit("setPinCommentAbortController", null); + commit("setPinnedCommentDetails", response); + }) + .catch((error) => { + commit("catchError", error); + commit("setPinCommentAbortController", null); + throw error; + }); }, /** * Add/remove/display anonymous requestor */ removeRequestor({ commit, dispatch }) { - const body = {}; - const url = `/api/1.0/person/accompanying-course/${id}/requestor.json`; + const body = {}; + const url = `/api/1.0/person/accompanying-course/${id}/requestor.json`; - return makeFetch('DELETE', url, body) - .then(() => { - commit('removeRequestor'); - dispatch('requestorIsAnonymous', false); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("DELETE", url, body) + .then(() => { + commit("removeRequestor"); + dispatch("requestorIsAnonymous", false); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, addRequestor({ commit }, payload) { - const body = payload ? { type: payload.result.type, id: payload.result.id } : {}; - const url = `/api/1.0/person/accompanying-course/${id}/requestor.json`; + const body = payload + ? { type: payload.result.type, id: payload.result.id } + : {}; + const url = `/api/1.0/person/accompanying-course/${id}/requestor.json`; - return makeFetch('POST', url, body) - .then((response) => { - commit('addRequestor', response); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("POST", url, body) + .then((response) => { + commit("addRequestor", response); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, requestorIsAnonymous({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json` - const body = { type: "accompanying_period", requestorAnonymous: payload } + const url = `/api/1.0/person/accompanying-course/${id}.json`; + const body = { + type: "accompanying_period", + requestorAnonymous: payload, + }; - return makeFetch('PATCH', url, body) - .then((response) => { - commit('requestorIsAnonymous', response.requestorAnonymous); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("PATCH", url, body) + .then((response) => { + commit("requestorIsAnonymous", response.requestorAnonymous); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, /** * Add/remove resource */ removeResource({ commit }, payload) { - const body = { type: "accompanying_period_resource" }; - body['id'] = payload.id; - const url = `/api/1.0/person/accompanying-course/${id}/resource.json`; + const body = { type: "accompanying_period_resource" }; + body["id"] = payload.id; + const url = `/api/1.0/person/accompanying-course/${id}/resource.json`; - return makeFetch('DELETE', url, body) - .then(() => { - commit('removeResource', payload) - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("DELETE", url, body) + .then(() => { + commit("removeResource", payload); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, addResource({ commit }, payload) { - const body = { type: "accompanying_period_resource" }; - body['resource'] = { type: payload.result.type, id: payload.result.id }; - const url = `/api/1.0/person/accompanying-course/${id}/resource.json`; + const body = { type: "accompanying_period_resource" }; + body["resource"] = { + type: payload.result.type, + id: payload.result.id, + }; + const url = `/api/1.0/person/accompanying-course/${id}/resource.json`; - return makeFetch('POST', url, body) - .then((response) => { - commit('addResource', response); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("POST", url, body) + .then((response) => { + commit("addResource", response); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, patchResource({ commit }, payload) { - const body = { type: "accompanying_period_resource" }; - body['resource'] = { - type: payload.result.type, - id: payload.result.id - }; - const url = `/api/1.0/person/accompanying-course/resource/${id}.json`; + const body = { type: "accompanying_period_resource" }; + body["resource"] = { + type: payload.result.type, + id: payload.result.id, + }; + const url = `/api/1.0/person/accompanying-course/resource/${id}.json`; - return makeFetch('PATCH', url, body) - .then((response) => { - commit('patchResource', response); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("PATCH", url, body) + .then((response) => { + commit("patchResource", response); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, /** * Update accompanying course intensity/emergency/confidentiality */ toggleIntensity({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}/intensity.json` - const body = { type: "accompanying_period", 'intensity': payload } + const url = `/api/1.0/person/accompanying-course/${id}/intensity.json`; + const body = { type: "accompanying_period", intensity: payload }; - return makeFetch('POST', url, body) - .then((response) => { - commit('toggleIntensity', response); - - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("POST", url, body) + .then((response) => { + commit("toggleIntensity", response); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, toggleEmergency({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json` - const body = { type: "accompanying_period", emergency: payload } + const url = `/api/1.0/person/accompanying-course/${id}.json`; + const body = { type: "accompanying_period", emergency: payload }; - return makeFetch('PATCH', url, body) - .then((response) => { - commit('toggleEmergency', response.emergency); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("PATCH", url, body) + .then((response) => { + commit("toggleEmergency", response.emergency); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, toggleConfidential({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}/confidential.json` - const body = { type: "accompanying_period", confidential: payload } + const url = `/api/1.0/person/accompanying-course/${id}/confidential.json`; + const body = { + type: "accompanying_period", + confidential: payload, + }; - console.log('url', url, 'body', body); + console.log("url", url, "body", body); - return makeFetch('POST', url, body) - .then((response) => { - console.log('response', response); - commit('toggleConfidential', response); - }) - .catch((error) => { - console.log('error', error) - commit('catchError', error); - throw error; - }) + return makeFetch("POST", url, body) + .then((response) => { + console.log("response", response); + commit("toggleConfidential", response); + }) + .catch((error) => { + console.log("error", error); + commit("catchError", error); + throw error; + }); }, /** * Handle the checked/unchecked scopes @@ -635,28 +714,35 @@ let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCou * @returns Promise */ setScopes({ commit, state, dispatch }, scopes) { - let currentServerScopesIds = state.scopesAtBackend.map(scope => scope.id); - let checkedScopesIds = scopes.map(scope => scope.id); - let removedScopesIds = currentServerScopesIds.filter(id => !checkedScopesIds.includes(id)); - let addedScopesIds = checkedScopesIds.filter(id => !currentServerScopesIds.includes(id)); + let currentServerScopesIds = state.scopesAtBackend.map( + (scope) => scope.id, + ); + let checkedScopesIds = scopes.map((scope) => scope.id); + let removedScopesIds = currentServerScopesIds.filter( + (id) => !checkedScopesIds.includes(id), + ); + let addedScopesIds = checkedScopesIds.filter( + (id) => !currentServerScopesIds.includes(id), + ); - return dispatch('updateScopes', { - addedScopesIds, removedScopesIds - }) - .catch(error => { + return dispatch("updateScopes", { + addedScopesIds, + removedScopesIds, + }) + .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); + commit("setScopes", scopes); return Promise.resolve(); - }) - .then(() => { - return dispatch('fetchReferrersSuggested'); - }); - /* + }) + .then(() => { + return dispatch("fetchReferrersSuggested"); + }); + /* else { return dispatch('setScopes', state.scopesAtStart).then(() => { commit('setScopes', scopes); @@ -679,251 +765,286 @@ let initPromise = (root) => Promise.all([getScopesPromise(root), accompanyingCou * @param removedScopesIds * @return Promise */ - updateScopes({ state, commit }, { addedScopesIds, removedScopesIds }) { - let promises = []; - const url = `/api/1.0/person/accompanying-course/${state.accompanyingCourse.id}/scope.json`; - state.scopes.forEach(scope => { - const body = { - id: scope.id, - type: scope.type - }; + updateScopes( + { state, commit }, + { addedScopesIds, removedScopesIds }, + ) { + let promises = []; + const url = `/api/1.0/person/accompanying-course/${state.accompanyingCourse.id}/scope.json`; + state.scopes.forEach((scope) => { + const body = { + id: scope.id, + type: scope.type, + }; - if (addedScopesIds.includes(scope.id)) { - promises.push( - makeFetch('POST', url, body) - .then((response) => { - commit('addScopeAtBackend', scope); - return response; - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) - ) - } - if (removedScopesIds.includes(scope.id)) { - promises.push( - makeFetch('DELETE', url, body) - .then((response) => { - commit('removeScopeAtBackend', scope); - return response; - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) - ); - } - }); + if (addedScopesIds.includes(scope.id)) { + promises.push( + makeFetch("POST", url, body) + .then((response) => { + commit("addScopeAtBackend", scope); + return response; + }) + .catch((error) => { + commit("catchError", error); + throw error; + }), + ); + } + if (removedScopesIds.includes(scope.id)) { + promises.push( + makeFetch("DELETE", url, body) + .then((response) => { + commit("removeScopeAtBackend", scope); + return response; + }) + .catch((error) => { + commit("catchError", error); + throw error; + }), + ); + } + }); - return Promise.all(promises); + return Promise.all(promises); }, patchFirstComment({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json`; - const body = { - type: "accompanying_period", - pinnedComment: { - type: "accompanying_period_comment", - id: payload.id - } - }; - return makeFetch('PATCH', url, body) - .catch((error) => { - commit('catchError', error); - throw error; - }); + const url = `/api/1.0/person/accompanying-course/${id}.json`; + const body = { + type: "accompanying_period", + pinnedComment: { + type: "accompanying_period_comment", + id: payload.id, + }, + }; + return makeFetch("PATCH", url, body).catch((error) => { + commit("catchError", error); + throw error; + }); }, - updateSocialIssues({ state, commit, dispatch }, { payload, body, method }) { - const url = `/api/1.0/person/accompanying-course/${id}/socialissue.json`; - return makeFetch(method, url, body) - .then(() => { - commit('updateSocialIssues', payload); - }) - .then(() => { - return getAccompanyingCourse(state.accompanyingCourse.id) - }) - .then(accompanying_course => { - commit('refreshSocialIssues', accompanying_course.socialIssues); - dispatch('fetchReferrersSuggested'); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + updateSocialIssues( + { state, commit, dispatch }, + { payload, body, method }, + ) { + const url = `/api/1.0/person/accompanying-course/${id}/socialissue.json`; + return makeFetch(method, url, body) + .then(() => { + commit("updateSocialIssues", payload); + }) + .then(() => { + return getAccompanyingCourse(state.accompanyingCourse.id); + }) + .then((accompanying_course) => { + commit( + "refreshSocialIssues", + accompanying_course.socialIssues, + ); + dispatch("fetchReferrersSuggested"); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, updateOrigin({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json`; - const body = { type: "accompanying_period", origin: { id: payload.id, type: payload.type }}; + const url = `/api/1.0/person/accompanying-course/${id}.json`; + const body = { + type: "accompanying_period", + origin: { id: payload.id, type: payload.type }, + }; - return makeFetch('PATCH', url, body) - .then((response) => { - commit('updateOrigin', response.origin); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("PATCH", url, body) + .then((response) => { + commit("updateOrigin", response.origin); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, updateAdminLocation({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json`; - const body = { type: "accompanying_period", administrativeLocation: { id: payload.id, type: payload.type }}; + const url = `/api/1.0/person/accompanying-course/${id}.json`; + const body = { + type: "accompanying_period", + administrativeLocation: { id: payload.id, type: payload.type }, + }; - return makeFetch('PATCH', url, body) - .then((response) => { - commit('updateAdminLocation', response.administrativeLocation); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("PATCH", url, body) + .then((response) => { + commit( + "updateAdminLocation", + response.administrativeLocation, + ); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, updateReferrer({ commit, state }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json`; - let body = { type: "accompanying_period", user: null }; + const url = `/api/1.0/person/accompanying-course/${id}.json`; + let body = { type: "accompanying_period", user: null }; - if (payload !== null) { - body = { type: "accompanying_period", user: { id: payload.id, type: payload.type } }; - } + if (payload !== null) { + body = { + type: "accompanying_period", + user: { id: payload.id, type: payload.type }, + }; + } - return makeFetch('PATCH', url, body) - .then((response) => { - commit('updateReferrer', response.user); - if (null !== payload && null !== payload.user_job && payload.user_job !== state.accompanyingCourse.job) { - this.dispatch('updateJob', payload.user_job); - } - // commit('setFilteredReferrersSuggested'); // this mutation doesn't exist? - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("PATCH", url, body) + .then((response) => { + commit("updateReferrer", response.user); + if ( + null !== payload && + null !== payload.user_job && + payload.user_job !== state.accompanyingCourse.job + ) { + this.dispatch("updateJob", payload.user_job); + } + // commit('setFilteredReferrersSuggested'); // this mutation doesn't exist? + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, updateJob({ commit }, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json`; - let body = { type: "accompanying_period", job: null }; + const url = `/api/1.0/person/accompanying-course/${id}.json`; + let body = { type: "accompanying_period", job: null }; - console.log('update job', payload); + console.log("update job", payload); - if (payload !== null) { - body = { type: "accompanying_period", job: { id: payload.id, type: payload.type } }; - } + if (payload !== null) { + body = { + type: "accompanying_period", + job: { id: payload.id, type: payload.type }, + }; + } - return makeFetch('PATCH', url, body) - .then((response) => { - commit('updateJob', response.job); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return makeFetch("PATCH", url, body) + .then((response) => { + commit("updateJob", response.job); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, - updateStartDate({commit}, payload) { - const url = `/api/1.0/person/accompanying-course/${id}.json`; - const date = payload === null || payload === '' ? null : { datetime: datetimeToISO(ISOToDate(payload)) } - const body = { type: "accompanying_period", openingDate: date}; - return makeFetch('PATCH', url, body) - .then((response) => { - commit('updateStartDate', response.openingDate); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + updateStartDate({ commit }, payload) { + const url = `/api/1.0/person/accompanying-course/${id}.json`; + const date = + payload === null || payload === "" + ? null + : { datetime: datetimeToISO(ISOToDate(payload)) }; + const body = { type: "accompanying_period", openingDate: date }; + return makeFetch("PATCH", url, body) + .then((response) => { + commit("updateStartDate", response.openingDate); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, - async fetchReferrersSuggested({ state, commit}) { - let users = await getReferrersSuggested(state.accompanyingCourse); - commit('setReferrersSuggested', users); - if ( - null === state.accompanyingCourse.user - && !state.accompanyingCourse.confidential - && !state.accompanyingCourse.step === 'DRAFT' - && users.length === 1 - ) { - // set the user if unique - commit('updateReferrer', users[0]); - } + async fetchReferrersSuggested({ state, commit }) { + let users = await getReferrersSuggested(state.accompanyingCourse); + commit("setReferrersSuggested", users); + if ( + null === state.accompanyingCourse.user && + !state.accompanyingCourse.confidential && + !state.accompanyingCourse.step === "DRAFT" && + users.length === 1 + ) { + // set the user if unique + commit("updateReferrer", users[0]); + } }, - async fetchUsers({commit}) { - let users = await getUsers(); - commit('setUsers', users); + async fetchUsers({ commit }) { + let users = await getUsers(); + commit("setUsers", users); }, /** * By adding more roles to body['roles'], more permissions can be checked. */ - fetchPermissions({commit}) { - const url = '/api/1.0/main/permissions/info.json'; - const body = { - "object": { - "type": "accompanying_period", - "id": id - }, - "class": "Chill\\PersonBundle\\Entity\\AccompanyingPeriod", - "roles": [ - "CHILL_PERSON_ACCOMPANYING_PERIOD_TOGGLE_CONFIDENTIAL" - ] - } + fetchPermissions({ commit }) { + const url = "/api/1.0/main/permissions/info.json"; + const body = { + object: { + type: "accompanying_period", + id: id, + }, + class: "Chill\\PersonBundle\\Entity\\AccompanyingPeriod", + roles: ["CHILL_PERSON_ACCOMPANYING_PERIOD_TOGGLE_CONFIDENTIAL"], + }; - return makeFetch('POST', url, body) - .then((response) => { - commit('setPermissions', response); + return makeFetch("POST", url, body) + .then((response) => { + commit("setPermissions", response); - return Promise.resolve(); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + return Promise.resolve(); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, updateLocation({ commit, dispatch }, payload) { - //console.log('## action: updateLocation', payload.locationStatusTo); - const url = `/api/1.0/person/accompanying-course/${payload.targetId}.json`; - let body = { 'type': payload.target, 'id': payload.targetId }; - let location = {}; - if (payload.locationStatusTo === 'person') { // patch for person address (don't remove addressLocation) - location = { 'personLocation': { 'type': 'person', 'id': payload.personId }}; - } - else if (payload.locationStatusTo === 'address') { // patch for temporary address - location = { 'personLocation': null, 'addressLocation': { 'id': payload.addressId }}; - } - else { // patch to remove person address - location = { 'personLocation': null }; - } - Object.assign(body, location); - makeFetch('PATCH', url, body) - .then((response) => { - commit('updateLocation', { - location: response.location, - locationStatus: response.locationStatus, - personLocation: response.personLocation - }); - dispatch('fetchReferrersSuggested'); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) + //console.log('## action: updateLocation', payload.locationStatusTo); + const url = `/api/1.0/person/accompanying-course/${payload.targetId}.json`; + let body = { type: payload.target, id: payload.targetId }; + let location = {}; + if (payload.locationStatusTo === "person") { + // patch for person address (don't remove addressLocation) + location = { + personLocation: { type: "person", id: payload.personId }, + }; + } else if (payload.locationStatusTo === "address") { + // patch for temporary address + location = { + personLocation: null, + addressLocation: { id: payload.addressId }, + }; + } else { + // patch to remove person address + location = { personLocation: null }; + } + Object.assign(body, location); + makeFetch("PATCH", url, body) + .then((response) => { + commit("updateLocation", { + location: response.location, + locationStatus: response.locationStatus, + personLocation: response.personLocation, + }); + dispatch("fetchReferrersSuggested"); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); }, confirmAccompanyingCourse({ commit }) { - const url = `/api/1.0/person/accompanying-course/${id}/confirm.json` - makeFetch('POST', url) - .then((response) => { - window.location.replace(`/fr/parcours/${id}`); - commit('confirmAccompanyingCourse', response); - }) - .catch((error) => { - commit('catchError', error); - throw error; - }) - } - } - }); + const url = `/api/1.0/person/accompanying-course/${id}/confirm.json`; + makeFetch("POST", url) + .then((response) => { + window.location.replace(`/fr/parcours/${id}`); + commit("confirmAccompanyingCourse", response); + }) + .catch((error) => { + commit("catchError", error); + throw error; + }); + }, + }, + }); - if (root === 'app') { - store.dispatch('fetchReferrersSuggested'); - store.dispatch('fetchUsers'); - } + if (root === "app") { + store.dispatch("fetchReferrersSuggested"); + store.dispatch("fetchUsers"); + } - resolve(store); - })); + resolve(store); + }), + ); export { initPromise }; diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkCreate/App.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkCreate/App.vue index e182e3158..f8b5389f4 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkCreate/App.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkCreate/App.vue @@ -1,23 +1,16 @@ - - diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddEvaluation.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddEvaluation.vue index 4f610815e..e5b46185e 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddEvaluation.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddEvaluation.vue @@ -1,22 +1,15 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddResult.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddResult.vue index 2d92ccf49..1f8913470 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddResult.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/AddResult.vue @@ -1,36 +1,20 @@ - diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/FormEvaluation.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/FormEvaluation.vue index 33b831224..139723885 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/FormEvaluation.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/components/FormEvaluation.vue @@ -19,55 +19,55 @@
+ />
+ />
+ />
+ />
+ />
-

- Créé par {{ d.createdBy.text }}
- Le {{ $d(ISOToDatetime(d.createdAt.datetime), 'long') }} +

+ Créé par {{ d.createdBy.text }}
+ Le {{ $d(ISOToDatetime(d.createdAt.datetime), "long") }}

@@ -157,8 +151,10 @@ :related-entity-id="d.id" :workflows-availables="d.workflows_availables" :prevent-default-move-to-generate="true" - :go-to-generate-workflow-payload="{doc: d}" - @go-to-generate-workflow="goToGenerateWorkflowEvaluationDocument" + :go-to-generate-workflow-payload="{ doc: d }" + @go-to-generate-workflow=" + goToGenerateWorkflowEvaluationDocument + " />
  • @@ -176,7 +172,7 @@ data-bs-toggle="dropdown" aria-expanded="false" > -  +   @@ -204,7 +202,9 @@ :can-edit="true" :execute-before-leave="submitBeforeLeaveToEditor" :dav-link="d.storedObject._links?.dav_link.href" - :dav-link-expiration="d.storedObject._links?.dav_link.expiration" + :dav-link-expiration=" + d.storedObject._links?.dav_link.expiration + " @on-stored-object-status-change="onStatusDocumentChanged" />
  • @@ -212,15 +212,12 @@
  • - +
  • @@ -230,7 +227,7 @@
    -
    {{ $t('document_add') }} :
    +
    {{ $t("document_add") }} :
    - +
    • diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/index.js b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/index.js index 88a8e5469..73540e5c8 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/index.js +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/index.js @@ -1,24 +1,24 @@ -import { createApp } from 'vue'; -import { _createI18n } from 'ChillMainAssets/vuejs/_js/i18n'; -import { store } from './store'; -import { personMessages } from 'ChillPersonAssets/vuejs/_js/i18n'; -import 'vue-toast-notification/dist/theme-sugar.css'; -import App from './App.vue'; +import { createApp } from "vue"; +import { _createI18n } from "ChillMainAssets/vuejs/_js/i18n"; +import { store } from "./store"; +import { personMessages } from "ChillPersonAssets/vuejs/_js/i18n"; +import "vue-toast-notification/dist/theme-sugar.css"; +import App from "./App.vue"; import ToastPlugin from "vue-toast-notification"; const i18n = _createI18n(personMessages); /* exported app */ const app = createApp({ - template: ``, + template: ``, }) -.use(store) -.use(ToastPlugin, { - position: "bottom-right", - type: "error", - duration: 10000, - dismissible: true -}) -.use(i18n) -.component('app', App) -.mount('#accompanying_course_work_edit'); + .use(store) + .use(ToastPlugin, { + position: "bottom-right", + type: "error", + duration: 10000, + dismissible: true, + }) + .use(i18n) + .component("app", App) + .mount("#accompanying_course_work_edit"); diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/store.js b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/store.js index 639b02a79..924367f9f 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/store.js +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/AccompanyingCourseWorkEdit/store.js @@ -1,18 +1,28 @@ -import { createStore } from 'vuex'; -import { dateToISO, ISOToDate, datetimeToISO, intervalDaysToISO, intervalISOToDays } from 'ChillMainAssets/chill/js/date'; -import { fetchResults, makeFetch } from 'ChillMainAssets/lib/api/apiMethods.ts'; -import { fetchTemplates } from 'ChillDocGeneratorAssets/api/pickTemplate.js'; +import { createStore } from "vuex"; +import { + dateToISO, + ISOToDate, + datetimeToISO, + intervalDaysToISO, + intervalISOToDays, +} from "ChillMainAssets/chill/js/date"; +import { fetchResults, makeFetch } from "ChillMainAssets/lib/api/apiMethods.ts"; +import { fetchTemplates } from "ChillDocGeneratorAssets/api/pickTemplate.js"; -const debug = process.env.NODE_ENV !== 'production'; +const debug = process.env.NODE_ENV !== "production"; const store = createStore({ strict: debug, state: { work: window.accompanyingCourseWork, - startDate: window.accompanyingCourseWork.startDate !== null ? - dateToISO(new Date(window.accompanyingCourseWork.startDate.datetime)) : null, - endDate: window.accompanyingCourseWork.endDate !== null ? - dateToISO(new Date(window.accompanyingCourseWork.endDate.datetime)) : null, + startDate: + window.accompanyingCourseWork.startDate !== null + ? dateToISO(new Date(window.accompanyingCourseWork.startDate.datetime)) + : null, + endDate: + window.accompanyingCourseWork.endDate !== null + ? dateToISO(new Date(window.accompanyingCourseWork.endDate.datetime)) + : null, note: window.accompanyingCourseWork.note, privateComment: window.accompanyingCourseWork.privateComment, goalsPicked: window.accompanyingCourseWork.goals, @@ -25,15 +35,17 @@ const store = createStore({ templatesAvailablesForAction: [], templatesAvailablesForEvaluation: new Map([]), personsPicked: window.accompanyingCourseWork.persons, - personsReachables: window.accompanyingCourseWork.accompanyingPeriod.participations.filter(p => p.endDate == null) - .map(p => p.person), + personsReachables: + window.accompanyingCourseWork.accompanyingPeriod.participations + .filter((p) => p.endDate == null) + .map((p) => p.person), handlingThirdParty: window.accompanyingCourseWork.handlingThierParty, thirdParties: window.accompanyingCourseWork.thirdParties, referrers: window.accompanyingCourseWork.referrers, isPosting: false, errors: [], me: null, - version: window.accompanyingCourseWork.version + version: window.accompanyingCourseWork.version, }, getters: { socialAction(state) { @@ -43,12 +55,12 @@ const store = createStore({ return state.resultsForAction.length > 0; }, resultsForGoal: (state) => (goal) => { - let founds = state.resultsForGoal.filter(r => r.goalId === goal.id); + let founds = state.resultsForGoal.filter((r) => r.goalId === goal.id); return founds === undefined ? [] : founds; }, resultsPickedForGoal: (state) => (goal) => { - let found = state.goalsPicked.find(g => g.goal.id === goal.id); + let found = state.goalsPicked.find((g) => g.goal.id === goal.id); return found === undefined ? [] : found.results; }, @@ -70,26 +82,38 @@ const store = createStore({ }, buildPayload(state) { return { - type: 'accompanying_period_work', + type: "accompanying_period_work", id: state.work.id, version: state.version, - startDate: state.startDate === null || state.startDate === '' ? null : { - datetime: datetimeToISO(ISOToDate(state.startDate)) - }, - endDate: state.endDate === null || state.endDate === '' ? null : { - datetime: datetimeToISO(ISOToDate(state.endDate)) - }, + startDate: + state.startDate === null || state.startDate === "" + ? null + : { + datetime: datetimeToISO(ISOToDate(state.startDate)), + }, + endDate: + state.endDate === null || state.endDate === "" + ? null + : { + datetime: datetimeToISO(ISOToDate(state.endDate)), + }, note: state.note, privateComment: state.privateComment, - persons: state.personsPicked.map(p => ({id: p.id, type: p.type})), - handlingThierParty: state.handlingThirdParty === null ? null : { - id: state.handlingThirdParty.id, - type: state.handlingThirdParty.type - }, - results: state.resultsPicked.map(r => ({id: r.id, type: r.type})), - thirdParties: state.thirdParties.map(t => ({id: t.id, type: t.type})), - referrers: state.referrers.map(t => ({id: t.id, type: t.type})), - goals: state.goalsPicked.map(g => { + persons: state.personsPicked.map((p) => ({ id: p.id, type: p.type })), + handlingThierParty: + state.handlingThirdParty === null + ? null + : { + id: state.handlingThirdParty.id, + type: state.handlingThirdParty.type, + }, + results: state.resultsPicked.map((r) => ({ id: r.id, type: r.type })), + thirdParties: state.thirdParties.map((t) => ({ + id: t.id, + type: t.type, + })), + referrers: state.referrers.map((t) => ({ id: t.id, type: t.type })), + goals: state.goalsPicked.map((g) => { let o = { type: g.type, note: g.note, @@ -97,55 +121,72 @@ const store = createStore({ type: g.goal.type, id: g.goal.id, }, - results: g.results.map(r => ({id: r.id, type: r.type})), + results: g.results.map((r) => ({ id: r.id, type: r.type })), }; if (g.id !== undefined) { o.id = g.id; } return o; }), - accompanyingPeriodWorkEvaluations: state.evaluationsPicked.map(e => { + accompanyingPeriodWorkEvaluations: state.evaluationsPicked.map((e) => { let o = { type: e.type, key: e.key, evaluation: { id: e.evaluation.id, - type: e.evaluation.type + type: e.evaluation.type, }, - startDate: e.startDate === null || e.startDate === '' ? null : { datetime: datetimeToISO(ISOToDate(e.startDate)) }, - endDate: e.endDate === null || e.endDate === '' ? null : { datetime: datetimeToISO(ISOToDate(e.endDate)) }, - maxDate: e.maxDate === null || e.maxDate === '' ? null : { datetime: datetimeToISO(ISOToDate(e.maxDate)) }, + startDate: + e.startDate === null || e.startDate === "" + ? null + : { datetime: datetimeToISO(ISOToDate(e.startDate)) }, + endDate: + e.endDate === null || e.endDate === "" + ? null + : { datetime: datetimeToISO(ISOToDate(e.endDate)) }, + maxDate: + e.maxDate === null || e.maxDate === "" + ? null + : { datetime: datetimeToISO(ISOToDate(e.maxDate)) }, warningInterval: intervalDaysToISO(e.warningInterval), timeSpent: e.timeSpent, comment: e.comment, - documents: e.documents + documents: e.documents, }; if (e.id !== undefined) { o.id = e.id; } return o; - }) + }), }; - } + }, }, mutations: { setWhoAmiI(state, me) { - state.me = me; + state.me = me; }, setEvaluationsPicked(state, evaluations) { state.evaluationsPicked = evaluations.map((e, index) => { var k = Object.assign(e, { key: index, editEvaluation: false, - startDate: e.startDate !== null ? dateToISO(new Date(e.startDate.datetime)) : null, - endDate: e.endDate !== null ? dateToISO(new Date(e.endDate.datetime)) : null, - maxDate: e.maxDate !== null ? dateToISO(new Date(e.maxDate.datetime)) : null, - warningInterval: e.warningInterval !== null ? intervalISOToDays(e.warningInterval) : null, + startDate: + e.startDate !== null + ? dateToISO(new Date(e.startDate.datetime)) + : null, + endDate: + e.endDate !== null ? dateToISO(new Date(e.endDate.datetime)) : null, + maxDate: + e.maxDate !== null ? dateToISO(new Date(e.maxDate.datetime)) : null, + warningInterval: + e.warningInterval !== null + ? intervalISOToDays(e.warningInterval) + : null, timeSpent: e.timeSpent !== null ? e.timeSpent : null, documents: e.documents.map((d, docIndex) => { return Object.assign(d, { - key: docIndex + key: docIndex, }); }), }); @@ -177,28 +218,30 @@ const store = createStore({ state.resultsPicked.push(result); }, removeResultPicked(state, result) { - state.resultsPicked = state.resultsPicked.filter(r => r.id !== result.id); + state.resultsPicked = state.resultsPicked.filter( + (r) => r.id !== result.id, + ); }, addGoal(state, goal) { let g = { type: "accompanying_period_work_goal", goal: goal, - note: '', - results: [] - } - const tmpIndex = () => { - let ar = state.goalsPicked.map(g => g.id), - s = Math.min(...ar); - return (s < 0) ? s : 0 + note: "", + results: [], }; - g.id = tmpIndex() -1 + const tmpIndex = () => { + let ar = state.goalsPicked.map((g) => g.id), + s = Math.min(...ar); + return s < 0 ? s : 0; + }; + g.id = tmpIndex() - 1; state.goalsPicked.push(g); }, removeGoal(state, goal) { - state.goalsPicked = state.goalsPicked.filter(g => g.id !== goal.id); + state.goalsPicked = state.goalsPicked.filter((g) => g.id !== goal.id); }, - addResultForGoalPicked(state, { goal, result}) { - let found = state.goalsPicked.find(g => g.goal.id === goal.id); + addResultForGoalPicked(state, { goal, result }) { + let found = state.goalsPicked.find((g) => g.goal.id === goal.id); if (found === undefined) { return; @@ -207,52 +250,63 @@ const store = createStore({ found.results.push(result); }, removeResultForGoalPicked(state, { goal, result }) { - let found = state.goalsPicked.find(g => g.goal.id === goal.id); + let found = state.goalsPicked.find((g) => g.goal.id === goal.id); if (found === undefined) { return; } - found.results = found.results.filter(r => r.id !== result.id); + found.results = found.results.filter((r) => r.id !== result.id); }, addDocument(state, payload) { - let evaluation = state.evaluationsPicked.find(e => e.key === payload.key); - evaluation.documents.push(Object.assign( - payload.document, { + let evaluation = state.evaluationsPicked.find( + (e) => e.key === payload.key, + ); + evaluation.documents.push( + Object.assign(payload.document, { key: evaluation.documents.length + 1, - workflows_availables: state.work.workflows_availables_evaluation_documents, + workflows_availables: + state.work.workflows_availables_evaluation_documents, workflows: [], - })); + }), + ); }, - removeDocument(state, {key, document}) { - let evaluation = state.evaluationsPicked.find(e => e.key === key); + removeDocument(state, { key, document }) { + let evaluation = state.evaluationsPicked.find((e) => e.key === key); if (evaluation === undefined) { return; } - evaluation.documents = evaluation.documents.filter(d => d.key !== document.key); + evaluation.documents = evaluation.documents.filter( + (d) => d.key !== document.key, + ); }, replaceDocument(state, payload) { - let evaluation = state.evaluationsPicked.find(e => e.key === payload.key); + let evaluation = state.evaluationsPicked.find( + (e) => e.key === payload.key, + ); if (evaluation === undefined) { return; } - let doc = evaluation.documents.find(d => d.key === payload.oldDocument.key); + let doc = evaluation.documents.find( + (d) => d.key === payload.oldDocument.key, + ); - if (typeof doc === 'undefined') { - console.error('doc not found'); + if (typeof doc === "undefined") { + console.error("doc not found"); } doc.storedObject = payload.document.storedObject; return; - let newDocument = Object.assign( - payload.document, { - key: evaluation.documents.length + 1, - workflows_availables: state.work.workflows_availables_evaluation_documents, - workflows: [], - } + let newDocument = Object.assign(payload.document, { + key: evaluation.documents.length + 1, + workflows_availables: + state.work.workflows_availables_evaluation_documents, + workflows: [], + }); + evaluation.documents = evaluation.documents.map((d) => + d.id === payload.oldDocument.id ? newDocument : d, ); - evaluation.documents = evaluation.documents.map(d => d.id === payload.oldDocument.id ? newDocument : d); }, addEvaluation(state, evaluation) { let e = { @@ -260,8 +314,8 @@ const store = createStore({ key: state.evaluationsPicked.length + 1, evaluation: evaluation, startDate: dateToISO(new Date()), - endDate: null, - maxDate: null, + endDate: null, + maxDate: null, warningInterval: null, timeSpent: null, comment: "", @@ -273,46 +327,43 @@ const store = createStore({ state.evaluationsPicked.push(e); }, removeEvaluation(state, evaluation) { - state.evaluationsPicked = state.evaluationsPicked.filter(e => e.key !== evaluation.key); + state.evaluationsPicked = state.evaluationsPicked.filter( + (e) => e.key !== evaluation.key, + ); }, - setEvaluationStartDate(state, {key, date}) { - state.evaluationsPicked.find(e => e.key === key) - .startDate = date; + setEvaluationStartDate(state, { key, date }) { + state.evaluationsPicked.find((e) => e.key === key).startDate = date; }, - setEvaluationEndDate(state, {key, date}) { - console.log('commit date', date) - state.evaluationsPicked.find(e => e.key === key) - .endDate = date; + setEvaluationEndDate(state, { key, date }) { + console.log("commit date", date); + state.evaluationsPicked.find((e) => e.key === key).endDate = date; }, - setEvaluationMaxDate(state, {key, date}) { - state.evaluationsPicked.find(e => e.key === key) - .maxDate = date; + setEvaluationMaxDate(state, { key, date }) { + state.evaluationsPicked.find((e) => e.key === key).maxDate = date; }, - setEvaluationWarningInterval(state, {key, days}) { - state.evaluationsPicked.find(e => e.key === key) - .warningInterval = days; + setEvaluationWarningInterval(state, { key, days }) { + state.evaluationsPicked.find((e) => e.key === key).warningInterval = days; }, - setEvaluationTimeSpent(state, {key, time}) { - state.evaluationsPicked.find(e => e.key === key) - .timeSpent = time; + setEvaluationTimeSpent(state, { key, time }) { + state.evaluationsPicked.find((e) => e.key === key).timeSpent = time; }, - setEvaluationComment(state, {key, comment}) { - state.evaluationsPicked.find(e => e.key === key) - .comment = comment; + setEvaluationComment(state, { key, comment }) { + state.evaluationsPicked.find((e) => e.key === key).comment = comment; }, - toggleEvaluationEdit(state, {key}) { - let evaluation = state.evaluationsPicked.find(e => e.key === key); + toggleEvaluationEdit(state, { key }) { + let evaluation = state.evaluationsPicked.find((e) => e.key === key); evaluation.editEvaluation = !evaluation.editEvaluation; }, - setTemplatesForEvaluation(state, {templates, evaluation}) { + setTemplatesForEvaluation(state, { templates, evaluation }) { state.templatesAvailablesForEvaluation.set(evaluation.id, templates); }, setTemplatesAvailablesForAction(state, templates) { state.templatesAvailablesForAction = templates; }, setPersonsPickedIds(state, ids) { - state.personsPicked = state.personsReachables - .filter(p => ids.includes(p.id)) + state.personsPicked = state.personsReachables.filter((p) => + ids.includes(p.id), + ); }, setNote(state, note) { state.note = note; @@ -325,8 +376,8 @@ const store = createStore({ }, addThirdParties(state, thirdParties) { // filter to remove existing thirdparties - let ids = state.thirdParties.map(t => t.id); - let unexistings = thirdParties.filter(t => !ids.includes(t.id)); + let ids = state.thirdParties.map((t) => t.id); + let unexistings = thirdParties.filter((t) => !ids.includes(t.id)); for (let i in unexistings) { state.thirdParties.push(unexistings[i]); @@ -334,27 +385,29 @@ const store = createStore({ }, updateThirdParty(state, thirdParty) { for (let t of state.thirdParties) { - if (t.id === thirdParty.id){ - state.thirdParties = state.thirdParties.filter(t => t.id !== thirdParty.id); + if (t.id === thirdParty.id) { + state.thirdParties = state.thirdParties.filter( + (t) => t.id !== thirdParty.id, + ); state.thirdParties.push(thirdParty); } } }, removeThirdParty(state, thirdParty) { - state.thirdParties = state.thirdParties - .filter(t => t.id !== thirdParty.id); + state.thirdParties = state.thirdParties.filter( + (t) => t.id !== thirdParty.id, + ); }, addReferrers(state, referrers) { - let ids = state.referrers.map(t => t.id); - let unexistings = referrers.filter(t => !ids.includes(t.id)); + let ids = state.referrers.map((t) => t.id); + let unexistings = referrers.filter((t) => !ids.includes(t.id)); for (let i in unexistings) { state.referrers.push(unexistings[i]); } }, removeReferrer(state, user) { - state.referrers = state.referrers - .filter(u => u.id !== user.id); + state.referrers = state.referrers.filter((u) => u.id !== user.id); }, setErrors(state, errors) { state.errors = errors; @@ -364,22 +417,24 @@ const store = createStore({ }, updateDocumentTitle(state, payload) { if (payload.id === 0) { - state.evaluationsPicked.find(e => e.key === payload.evaluationKey) - .documents.find(d => d.key === payload.key).title = payload.title; + state.evaluationsPicked + .find((e) => e.key === payload.evaluationKey) + .documents.find((d) => d.key === payload.key).title = payload.title; } else { - state.evaluationsPicked.find(e => e.key === payload.evaluationKey) - .documents.find(d => d.id === payload.id).title = payload.title; + state.evaluationsPicked + .find((e) => e.key === payload.evaluationKey) + .documents.find((d) => d.id === payload.id).title = payload.title; } }, - statusDocumentChanged(state, {newStatus, key}) { - const e = state.evaluationsPicked.find(e => e.key === key); - if (typeof e === 'undefined') { - console.error('evaluation not found for given key', {key}); + statusDocumentChanged(state, { newStatus, key }) { + const e = state.evaluationsPicked.find((e) => e.key === key); + if (typeof e === "undefined") { + console.error("evaluation not found for given key", { key }); } - const doc = e.documents.find(d => d.storedObject?.id === newStatus.id); - if (typeof doc === 'undefined') { - console.error('document not found', {newStatus}); + const doc = e.documents.find((d) => d.storedObject?.id === newStatus.id); + if (typeof doc === "undefined") { + console.error("document not found", { newStatus }); } doc.storedObject.status = newStatus.status; @@ -389,160 +444,184 @@ const store = createStore({ }, actions: { getWhoAmI({ commit }) { - let url = `/api/1.0/main/whoami.json`; - window.fetch(url) - .then(response => { - if (response.ok) { - return response.json(); - } - throw { m: 'Error while retriving results for goal', s: response.status, b: response.body }; - }) - .then(data => { - commit('setWhoAmiI', data); - }); - }, - updateThirdParty({ commit }, payload) { - commit('updateThirdParty', payload); - }, - getReachablesGoalsForAction({ getters, commit, dispatch }) { - let - socialActionId = getters.socialAction.id, - url = `/api/1.0/person/social-work/goal/by-social-action/${socialActionId}.json` - ; + let url = `/api/1.0/main/whoami.json`; window - .fetch( - url - ).then( response => { + .fetch(url) + .then((response) => { if (response.ok) { return response.json(); } - throw { m: 'Error while retriving goal for social action', s: response.status, b: response.body }; - }).then( data => { - for (let i in data.results) { - dispatch('getReachablesResultsForGoal', data.results[i]); - } - }).catch( errors => { - commit('addErrors', errors); + throw { + m: "Error while retriving results for goal", + s: response.status, + b: response.body, + }; + }) + .then((data) => { + commit("setWhoAmiI", data); + }); + }, + updateThirdParty({ commit }, payload) { + commit("updateThirdParty", payload); + }, + getReachablesGoalsForAction({ getters, commit, dispatch }) { + let socialActionId = getters.socialAction.id, + url = `/api/1.0/person/social-work/goal/by-social-action/${socialActionId}.json`; + window + .fetch(url) + .then((response) => { + if (response.ok) { + return response.json(); + } + throw { + m: "Error while retriving goal for social action", + s: response.status, + b: response.body, + }; + }) + .then((data) => { + for (let i in data.results) { + dispatch("getReachablesResultsForGoal", data.results[i]); + } + }) + .catch((errors) => { + commit("addErrors", errors); }); }, getReachablesResultsForGoal({ commit }, goal) { - let - url = `/api/1.0/person/social-work/result/by-goal/${goal.id}.json` - ; - window.fetch(url) - .then(response => { + let url = `/api/1.0/person/social-work/result/by-goal/${goal.id}.json`; + window + .fetch(url) + .then((response) => { if (response.ok) { return response.json(); } - throw { m: 'Error while retriving results for goal', s: response.status, b: response.body }; + throw { + m: "Error while retriving results for goal", + s: response.status, + b: response.body, + }; }) - .then(data => { - commit('setResultsForGoal', { goal, results: data.results }); + .then((data) => { + commit("setResultsForGoal", { goal, results: data.results }); }); }, getReachablesResultsForAction({ getters, commit }) { - let - socialActionId = getters.socialAction.id, - url = `/api/1.0/person/social-work/result/by-social-action/${socialActionId}.json` - ; - window.fetch(url) - .then(response => { + let socialActionId = getters.socialAction.id, + url = `/api/1.0/person/social-work/result/by-social-action/${socialActionId}.json`; + window + .fetch(url) + .then((response) => { if (response.ok) { return response.json(); } - throw { m: 'Error while retriving results for social action', s: response.status, b: response.body }; + throw { + m: "Error while retriving results for social action", + s: response.status, + b: response.body, + }; }) - .then(data => { - commit('setResultsForAction', data.results); + .then((data) => { + commit("setResultsForAction", data.results); }); }, getReachablesEvaluationsForAction({ getters, commit }) { - let - socialActionId = getters.socialAction.id, - url = `/api/1.0/person/social-work/evaluation/by-social-action/${socialActionId}.json` - ; - window.fetch(url) - .then(response => { + let socialActionId = getters.socialAction.id, + url = `/api/1.0/person/social-work/evaluation/by-social-action/${socialActionId}.json`; + window + .fetch(url) + .then((response) => { if (response.ok) { return response.json(); } - throw { m: 'Error while retriving evaluations for social action', s: response.status, b: response.body }; + throw { + m: "Error while retriving evaluations for social action", + s: response.status, + b: response.body, + }; }) - .then(data => { - commit('setEvaluationsForAction', data.results); + .then((data) => { + commit("setEvaluationsForAction", data.results); }); }, - addEvaluation({commit, dispatch}, evaluation) { - commit('addEvaluation', evaluation); - dispatch('fetchTemplatesAvailablesForEvaluation', evaluation); + addEvaluation({ commit, dispatch }, evaluation) { + commit("addEvaluation", evaluation); + dispatch("fetchTemplatesAvailablesForEvaluation", evaluation); }, - fetchTemplatesAvailablesForEvaluation({commit, state}, evaluation) { + fetchTemplatesAvailablesForEvaluation({ commit, state }, evaluation) { if (!state.templatesAvailablesForEvaluation.has(evaluation.id)) { // commit an empty array to avoid parallel fetching for same evaluation id - commit('setTemplatesForEvaluation', {templates: [], evaluation}); - fetchResults(`/api/1.0/person/docgen/template/by-evaluation/${evaluation.id}.json`) - .then(templates => { - commit('setTemplatesForEvaluation', {templates, evaluation}); - }); + commit("setTemplatesForEvaluation", { templates: [], evaluation }); + fetchResults( + `/api/1.0/person/docgen/template/by-evaluation/${evaluation.id}.json`, + ).then((templates) => { + commit("setTemplatesForEvaluation", { templates, evaluation }); + }); } }, - addDocument({commit}, payload) { - commit('addDocument', payload); + addDocument({ commit }, payload) { + commit("addDocument", payload); }, - removeDocument({commit}, payload) { - commit('removeDocument', payload); + removeDocument({ commit }, payload) { + commit("removeDocument", payload); }, - replaceDocument({commit}, payload) { - commit('replaceDocument', payload); + replaceDocument({ commit }, payload) { + commit("replaceDocument", payload); }, submit({ getters, state, commit }, callback) { - let - payload = getters.buildPayload, - params = new URLSearchParams({'entity_version': state.version}), - url = `/api/1.0/person/accompanying-course/work/${state.work.id}.json?${params}` - ; - - commit('setIsPosting', true); + let payload = getters.buildPayload, + params = new URLSearchParams({ entity_version: state.version }), + url = `/api/1.0/person/accompanying-course/work/${state.work.id}.json?${params}`; + commit("setIsPosting", true); // console.log('the social action', payload); - return makeFetch('PUT', url, payload) - .then(data => { - if (typeof(callback) !== 'undefined') { + return makeFetch("PUT", url, payload) + .then((data) => { + if (typeof callback !== "undefined") { return callback(data); } else { // console.log('payload', payload.privateComment) // console.info('nothing to do here, bye bye'); - window.location.assign(`/fr/person/accompanying-period/${state.work.accompanyingPeriod.id}/work`); + window.location.assign( + `/fr/person/accompanying-period/${state.work.accompanyingPeriod.id}/work`, + ); } - }).catch(error => { - console.log('error', error) - commit('setIsPosting', false); + }) + .catch((error) => { + console.log("error", error); + commit("setIsPosting", false); throw error; }); }, - updateDocumentTitle({commit}, payload) { - commit('updateDocumentTitle', payload) - } - } + updateDocumentTitle({ commit }, payload) { + commit("updateDocumentTitle", payload); + }, + }, }); -store.commit('setEvaluationsPicked', window.accompanyingCourseWork.accompanyingPeriodWorkEvaluations); -store.dispatch('getReachablesResultsForAction'); -store.dispatch('getReachablesGoalsForAction'); -store.dispatch('getReachablesEvaluationsForAction'); -store.dispatch('getWhoAmI'); +store.commit( + "setEvaluationsPicked", + window.accompanyingCourseWork.accompanyingPeriodWorkEvaluations, +); +store.dispatch("getReachablesResultsForAction"); +store.dispatch("getReachablesGoalsForAction"); +store.dispatch("getReachablesEvaluationsForAction"); +store.dispatch("getWhoAmI"); -store.state.evaluationsPicked.forEach(evaluation => { - store.dispatch('fetchTemplatesAvailablesForEvaluation', evaluation.evaluation) +store.state.evaluationsPicked.forEach((evaluation) => { + store.dispatch( + "fetchTemplatesAvailablesForEvaluation", + evaluation.evaluation, + ); }); -fetchTemplates('Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWork') - .then(templates => { - store.commit('setTemplatesAvailablesForAction', templates); - } -) +fetchTemplates( + "Chill\\PersonBundle\\Entity\\AccompanyingPeriod\\AccompanyingPeriodWork", +).then((templates) => { + store.commit("setTemplatesAvailablesForAction", templates); +}); export { store }; diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/ExportFormActionGoalResult/App.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/ExportFormActionGoalResult/App.vue index 0069cfb30..862c81926 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/ExportFormActionGoalResult/App.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/ExportFormActionGoalResult/App.vue @@ -1,11 +1,8 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/api.js b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/api.js index b42e57fe6..c4b21b614 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/api.js +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/api.js @@ -1,55 +1,60 @@ /* -*/ + */ const householdMove = (payload) => { const url = `/api/1.0/person/household/members/move.json`; console.log(payload); console.log(JSON.stringify(payload)); return fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify(payload), - }) - .then(response => { - if (response.ok) { - return response.json(); - } - if (response.status === 422) { - return response.json(); - } - throw Error('Error with testing move'); - }); + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(payload), + }).then((response) => { + if (response.ok) { + return response.json(); + } + if (response.status === 422) { + return response.json(); + } + throw Error("Error with testing move"); + }); }; const fetchHouseholdSuggestionByAccompanyingPeriod = (personId) => { const url = `/api/1.0/person/household/suggest/by-person/${personId}/through-accompanying-period-participation.json`; - return window.fetch(url) - .then(response => { + return window + .fetch(url) + .then((response) => { if (response.ok) { return response.json(); } - throw Error ({m: 'Error while fetching household suggestion', status: response.status}); - }).then(data => Promise.resolve(data.results)) - .catch(e => console.error(e)); - ; + throw Error({ + m: "Error while fetching household suggestion", + status: response.status, + }); + }) + .then((data) => Promise.resolve(data.results)) + .catch((e) => console.error(e)); }; const fetchAddressSuggestionByPerson = (personId) => { const url = `/api/1.0/person/address/suggest/by-person/${personId}.json`; - return window.fetch(url) - .then(response => { - if (response.ok) { - return response.json(); - } + return window.fetch(url).then((response) => { + if (response.ok) { + return response.json(); + } - throw Error({m: 'Error while fetch address suggestion', status: response.status}); + throw Error({ + m: "Error while fetch address suggestion", + status: response.status, }); -} + }); +}; -export { +export { householdMove, fetchHouseholdSuggestionByAccompanyingPeriod, fetchAddressSuggestionByPerson, diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Concerned.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Concerned.vue index c02d5f936..ae422f150 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Concerned.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Concerned.vue @@ -1,22 +1,22 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Confirmation.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Confirmation.vue index 5826e3a24..5441bc1af 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Confirmation.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Confirmation.vue @@ -1,48 +1,36 @@ - + diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/CurrentHousehold.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/CurrentHousehold.vue index 83578b937..3ae8c1ab6 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/CurrentHousehold.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/CurrentHousehold.vue @@ -1,16 +1,10 @@ - + diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Dates.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Dates.vue index 83c27710f..854db2058 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Dates.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Dates.vue @@ -1,28 +1,23 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Household.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Household.vue index 078fa5106..704adf94b 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Household.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/Household.vue @@ -1,35 +1,27 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/HouseholdAddress.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/HouseholdAddress.vue index bb0b5eb58..c7d9d8aac 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/HouseholdAddress.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/HouseholdAddress.vue @@ -16,20 +16,17 @@ />
    • -
    - + diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/MemberDetails.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/MemberDetails.vue index 0f281b078..006f8b219 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/MemberDetails.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/MemberDetails.vue @@ -8,15 +8,14 @@ :options="{}" :person="conc.person" /> - - {{ $t('household_members_editor.holder') }} + + {{ $t("household_members_editor.holder") }}
    - {{ $t('person.born', {'gender': conc.person.gender.genderTranslation} ) }} + {{ + $t("person.born", { gender: conc.person.gender.genderTranslation }) + }}
    @@ -30,33 +29,33 @@
    - +
    -
    +
    -
    @@ -66,7 +65,7 @@ @click="removeConcerned" class="btn btn-primary" > - {{ $t('household_members_editor.remove_concerned') }} + {{ $t("household_members_editor.remove_concerned") }}
    @@ -74,7 +73,6 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/PersonComment.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/PersonComment.vue index b13539526..aa87fe23e 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/PersonComment.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/HouseholdMembersEditor/components/PersonComment.vue @@ -1,7 +1,9 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/PersonSuggestion.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/PersonSuggestion.vue index 7005ba833..ac47390da 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/PersonSuggestion.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/PersonSuggestion.vue @@ -1,8 +1,5 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypePerson.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypePerson.vue index 457719541..773609316 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypePerson.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypePerson.vue @@ -3,54 +3,41 @@ - - {{ $d(item.result.birthdate.datetime, 'short') }} + + {{ $d(item.result.birthdate.datetime, "short") }} - + {{ item.result.current_household_address.text }} - {{ item.result.current_household_address.postcode.name }}
    - - + +
    diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypeThirdParty.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypeThirdParty.vue index 4c31613d9..bbcc553d0 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypeThirdParty.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/AddPersons/TypeThirdParty.vue @@ -1,13 +1,10 @@ diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/HouseholdRenderBox.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/HouseholdRenderBox.vue index 4e1f66295..a9d937250 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/HouseholdRenderBox.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/HouseholdRenderBox.vue @@ -3,19 +3,13 @@
    -
    +
    - {{ $t('new_household') }} + {{ $t("new_household") }}
    -
    +
    - {{ $t('household_number', { number: household.id } ) }} + {{ $t("household_number", { number: household.id }) }}
    @@ -30,32 +24,27 @@ v-for="m in currentMembers()" :key="m.id" class="m" - :class="{ is_new: m.is_new === true}" + :class="{ is_new: m.is_new === true }" > - diff --git a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/PersonRenderBox.vue b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/PersonRenderBox.vue index 0e7894dca..e27e2acfb 100644 --- a/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/PersonRenderBox.vue +++ b/src/Bundle/ChillPersonBundle/Resources/public/vuejs/_components/Entity/PersonRenderBox.vue @@ -1,55 +1,49 @@