Form.vue 12 KB

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