Form.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. <!--
  2. Formulaire générique
  3. Assure la validation des données, les actions de base (enregistrement, annulation, ...), et la confirmation avant
  4. de quitter si des données ont été modifiées.
  5. @see https://vuetifyjs.com/en/components/forms/#usage
  6. -->
  7. <template>
  8. <LayoutContainer>
  9. <v-form
  10. ref="form"
  11. v-model="isValid"
  12. :readonly="readonly"
  13. @submit.prevent=""
  14. >
  15. <!-- Top action bar -->
  16. <v-container
  17. v-if="actionPosition === 'both' || actionPosition === 'top'"
  18. :fluid="true"
  19. class="container btnActions"
  20. >
  21. <v-row>
  22. <v-col cols="12" sm="12">
  23. <slot name="form.button" />
  24. <UiButtonSubmit
  25. v-if="!readonly"
  26. :actions="actions"
  27. :validation-pending="validationPending || !isValid"
  28. @submit="submit"
  29. />
  30. </v-col>
  31. </v-row>
  32. </v-container>
  33. <div v-else class="mt-6" />
  34. <!-- Content -->
  35. <slot v-bind="{ modelValue }" />
  36. <!-- Bottom action bar -->
  37. <v-container
  38. v-if="actionPosition === 'both' || actionPosition === 'bottom'"
  39. :fluid="true"
  40. class="container btnActions"
  41. >
  42. <v-row>
  43. <v-col cols="12" sm="12">
  44. <slot name="form.button" />
  45. <UiButtonSubmit
  46. :validation-pending="validationPending || !isValid"
  47. :actions="actions"
  48. @submit="submit"
  49. />
  50. </v-col>
  51. </v-row>
  52. </v-container>
  53. </v-form>
  54. <!-- Confirmation dialog -->
  55. <LazyLayoutDialog :show="isConfirmationDialogShowing" :max-width="1000">
  56. <template #dialogText>
  57. <v-card-title class="text-h5 theme-neutral">
  58. {{ $t('caution') }}
  59. </v-card-title>
  60. <v-card-text>
  61. <br />
  62. <p>{{ $t('quit_without_saving_warning') }}.</p>
  63. </v-card-text>
  64. </template>
  65. <template #dialogBtn>
  66. <div class="confirmation-dlg-actions">
  67. <v-btn class="theme-neutral" @click="closeConfirmationDialog">
  68. {{ $t('cancel') }}
  69. </v-btn>
  70. <v-btn class="theme-danger" @click="cancel">
  71. {{ $t('quit_with_no_saving') }}
  72. </v-btn>
  73. <v-btn class="theme-primary" @click="saveAndQuit">
  74. {{ $t('save_and_quit') }}
  75. </v-btn>
  76. </div>
  77. </template>
  78. </LazyLayoutDialog>
  79. </LayoutContainer>
  80. </template>
  81. <script setup lang="ts">
  82. import { computed, ref, watch } from 'vue'
  83. import type { ComputedRef, Ref, PropType } from 'vue'
  84. import type { RouteLocationNormalized, RouteLocationRaw } from 'vue-router'
  85. import * as _ from 'lodash-es'
  86. import { FORM_FUNCTION, SUBMIT_TYPE, TYPE_ALERT } from '~/types/enum/enums'
  87. import { useFormStore } from '~/stores/form'
  88. import { useEntityManager } from '~/composables/data/useEntityManager'
  89. import type ApiModel from '~/models/ApiModel'
  90. import { usePageStore } from '~/stores/page'
  91. import type { AnyJson } from '~/types/data'
  92. import { useRefreshProfile } from '~/composables/data/useRefreshProfile'
  93. import Organization from '~/models/Freemium/Organization'
  94. import type Event from '~/models/Freemium/Event'
  95. import Country from '~/models/Core/Country'
  96. const props = defineProps({
  97. /**
  98. * Instance de l'ApiModel
  99. */
  100. modelValue: {
  101. type: Object as () => ApiModel,
  102. required: true,
  103. },
  104. /**
  105. * TODO: compléter
  106. */
  107. onChanged: {
  108. type: Function,
  109. required: false,
  110. default: null,
  111. },
  112. goBackRoute: {
  113. type: Object as PropType<RouteLocationRaw>,
  114. required: false,
  115. default: null,
  116. },
  117. /**
  118. * Types de soumission disponibles (enregistrer / enregistrer et quitter)
  119. */
  120. submitActions: {
  121. type: Object,
  122. required: false,
  123. default: () => {
  124. const actions: AnyJson = {}
  125. actions[SUBMIT_TYPE.SAVE] = {}
  126. return actions
  127. },
  128. },
  129. /**
  130. * La validation est en cours
  131. */
  132. validationPending: {
  133. type: Boolean,
  134. required: false,
  135. default: false,
  136. },
  137. /**
  138. * Faut-il rafraichir le profil à la soumission du formulaire ?
  139. */
  140. refreshProfileOnSubmit: {
  141. type: Boolean,
  142. required: false,
  143. default: false,
  144. },
  145. actionPosition: {
  146. type: String as PropType<'top' | 'bottom' | 'both'>,
  147. required: false,
  148. default: 'bottom',
  149. },
  150. })
  151. // ### Définitions
  152. const i18n = useI18n()
  153. const router = useRouter()
  154. const { em } = useEntityManager()
  155. const { refreshProfile } = useRefreshProfile()
  156. // Le formulaire est-il valide
  157. const isValid: Ref<boolean> = ref(true)
  158. // Erreurs de validation
  159. const errors: Ref<Array<string>> = ref([])
  160. // Référence au component v-form
  161. const form: Ref = ref(null)
  162. const formStore = useFormStore()
  163. // Le formulaire est-il en lecture seule
  164. const readonly: ComputedRef<boolean> = computed(() => {
  165. return formStore.readonly
  166. })
  167. /**
  168. * Si l'utilisateur veut quitter le formulaire sans enregistrer ses modifications,
  169. * on affiche la fenêtre de confirmation. En attendant, on garde en mémoire la route qu'il
  170. * voulait suivre au cas où il confirmerait.
  171. */
  172. const requestedLeavingRoute: Ref<RouteLocationNormalized | null> = ref(null)
  173. // La fenêtre de confirmation est-elle affichée
  174. const isConfirmationDialogShowing: ComputedRef<boolean> = computed(() => {
  175. return formStore.showConfirmToLeave
  176. })
  177. /**
  178. * Ferme la fenêtre de confirmation
  179. */
  180. const closeConfirmationDialog = () => {
  181. requestedLeavingRoute.value = null
  182. formStore.setShowConfirmToLeave(false)
  183. }
  184. const emit = defineEmits(['update:model-value'])
  185. // ### Actions du formulaire
  186. /**
  187. * Soumet le formulaire
  188. *
  189. * @param next
  190. */
  191. const submit = async (next: string | null = null) => {
  192. if (props.validationPending) {
  193. return
  194. }
  195. // Valide les données
  196. await validate()
  197. if (!isValid.value) {
  198. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  199. return
  200. }
  201. try {
  202. usePageStore().loading = true
  203. const updatedEntity = await em.persist(props.modelValue)
  204. emit('update:model-value', updatedEntity)
  205. if (props.refreshProfileOnSubmit) {
  206. await refreshProfile()
  207. }
  208. usePageStore().addAlert(TYPE_ALERT.SUCCESS, ['saveSuccess'])
  209. // On retire l'état 'dirty'
  210. setIsDirty(false)
  211. const actionArgs = next ? props.submitActions[next] : null
  212. if (next === SUBMIT_TYPE.SAVE) {
  213. onSaveAction(actionArgs, updatedEntity.id)
  214. } else if (next === SUBMIT_TYPE.SAVE_AND_BACK) {
  215. onSaveAndQuitAction(actionArgs)
  216. }
  217. } catch (error: unknown) {
  218. const err = error as {
  219. response?: {
  220. status: number
  221. _data: { violations?: Array<{ message: string; propertyPath: string }> }
  222. }
  223. }
  224. if (
  225. err.response &&
  226. err.response.status === 422 &&
  227. err.response._data.violations
  228. ) {
  229. // TODO: à revoir
  230. const violations: Array<string> = []
  231. let fields: AnyJson = {}
  232. for (const violation of err.response._data.violations) {
  233. violations.push(i18n.t(violation.message) as string)
  234. fields = Object.assign(fields, {
  235. [violation.propertyPath]: violation.message,
  236. })
  237. }
  238. formStore.addViolation(fields)
  239. usePageStore().addAlert(TYPE_ALERT.ALERT, ['invalid_form'])
  240. } else {
  241. throw error
  242. }
  243. } finally {
  244. usePageStore().loading = false
  245. }
  246. }
  247. /**
  248. * Enregistre et quitte
  249. */
  250. const saveAndQuit = async () => {
  251. await submit()
  252. cancel()
  253. }
  254. /**
  255. * Après l'action Sauvegarder
  256. *
  257. * Si on était en mode édition, on reste sur cette page (on ne fait rien).
  258. * Si on était en mode création, on bascule sur le mode édition
  259. *
  260. * @param route
  261. * @param id
  262. */
  263. function onSaveAction(route: Route, id: number) {
  264. if (formStore.formFunction === FORM_FUNCTION.CREATE) {
  265. route.path += id
  266. navigateTo(route)
  267. }
  268. }
  269. /**
  270. * Après l'action Sauvegarder et Quitter
  271. *
  272. * On redirige vers la route donnée
  273. *
  274. * @param route
  275. */
  276. function onSaveAndQuitAction(route: Route) {
  277. navigateTo(route)
  278. }
  279. /**
  280. * Avant de quitter le formulaire, si le formulaire a été modifié, on demande confirmation
  281. */
  282. onBeforeRouteLeave(
  283. (to: RouteLocationNormalized, from: RouteLocationNormalized) => {
  284. if (formStore.dirty === true) {
  285. requestedLeavingRoute.value = to
  286. formStore.setShowConfirmToLeave(true)
  287. return false
  288. }
  289. return true
  290. },
  291. )
  292. onMounted(() => {
  293. window.addEventListener('beforeunload', quitWithoutSaving)
  294. })
  295. onBeforeUnmount(() => {
  296. window.removeEventListener('beforeunload', quitWithoutSaving)
  297. })
  298. function quitWithoutSaving(event) {
  299. if (formStore.dirty === true) {
  300. event.returnValue = i18n.t('quit_without_saving_warning')
  301. }
  302. }
  303. /**
  304. * Quitte le formulaire sans enregistrer
  305. */
  306. const cancel = () => {
  307. setIsDirty(false)
  308. formStore.setShowConfirmToLeave(false)
  309. em.reset(props.modelValue)
  310. if (requestedLeavingRoute.value !== null) {
  311. navigateTo(requestedLeavingRoute.value)
  312. } else if (formStore.goAfterLeave !== null) {
  313. router.push(formStore.goAfterLeave) // TODO: voir si on peut pas passer ça comme prop du component
  314. }
  315. }
  316. const actions = computed(() => {
  317. return _.keys(props.submitActions)
  318. })
  319. // #### Validation et store
  320. /**
  321. * Update store when form is changed (if valid)
  322. */
  323. const onFormChange = async () => {
  324. if (isValid.value) {
  325. em.save(props.modelValue)
  326. setIsDirty(true)
  327. if (props.onChanged) {
  328. // Execute the custom onChange method, if defined
  329. // TODO: voir quelles variables passer à cette méthode custom ; d'ailleurs, vérifier aussi si cette méthode est utilisée
  330. props.onChanged()
  331. }
  332. }
  333. }
  334. /**
  335. * Utilise la méthode validate() de v-form pour valider le formulaire et mettre à jour les variables isValid et errors
  336. *
  337. * @see https://vuetifyjs.com/en/api/v-form/#functions-validate
  338. */
  339. const validate = async function () {
  340. const validation = await form.value.validate()
  341. isValid.value = validation.valid
  342. errors.value = validation.errors
  343. }
  344. // #### Gestion de l'état dirty
  345. const unwatch = watch(
  346. // /!\ Important de passer par un getter de l'objet (le `() => ({ ...props.modelValue })`),
  347. // car on perd la réactivité de celui-ci quand on soumet le formulaire
  348. // (et donc le watcher cesse de fonctionner)
  349. () => ({ ...props.modelValue }),
  350. (newEntity, oldEntity) => {
  351. if (JSON.stringify(newEntity) !== JSON.stringify(oldEntity)) {
  352. setIsDirty(true)
  353. }
  354. },
  355. )
  356. /**
  357. * Handle events if the form is dirty to prevent submission
  358. * @param e
  359. */
  360. // TODO: voir si encore nécessaire avec le @submit.prevent
  361. const preventSubmit = (e: Event) => {
  362. // Cancel the event
  363. e.preventDefault()
  364. // Chrome requires returnValue to be set
  365. const event = e as { returnValue: string }
  366. event.returnValue = ''
  367. }
  368. /**
  369. * Applique ou retire l'état dirty (modifié) du formulaire
  370. */
  371. const setIsDirty = (dirty: boolean) => {
  372. formStore.setDirty(dirty)
  373. }
  374. // Nettoyer les données lors du démontage du composant
  375. onBeforeUnmount(() => {
  376. unwatch()
  377. })
  378. defineExpose({ validate })
  379. </script>
  380. <style scoped>
  381. .btnActions {
  382. text-align: right;
  383. @media (max-width: 600px) {
  384. :deep(.v-col-12) {
  385. display: flex;
  386. flex-direction: column;
  387. justify-content: center;
  388. align-items: center;
  389. width: 100%;
  390. .v-btn {
  391. margin: 12px 0 !important;
  392. max-width: 250px;
  393. }
  394. }
  395. }
  396. }
  397. .confirmation-dlg-actions {
  398. display: flex;
  399. flex-direction: row;
  400. }
  401. .confirmation-dlg-actions .v-btn {
  402. min-width: 255px;
  403. max-width: 255px;
  404. margin: 0 8px;
  405. font-size: 13px;
  406. font-weight: 600;
  407. }
  408. @media (max-width: 960px) {
  409. .confirmation-dlg-actions {
  410. width: 100%;
  411. flex-direction: column;
  412. align-items: center;
  413. }
  414. .confirmation-dlg-actions .v-btn {
  415. min-width: 80%;
  416. max-width: 80%;
  417. margin: 6px 0 !important;
  418. }
  419. }
  420. </style>