TicketCreate.vue 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. <!-- Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/ -->
  2. <script setup lang="ts">
  3. import { computed, nextTick, reactive, ref, watch } from 'vue'
  4. import { onBeforeRouteLeave, useRouter } from 'vue-router'
  5. import { useEventListener } from '@vueuse/core'
  6. import Form from '@shared/components/Form/Form.vue'
  7. import {
  8. EnumFormUpdaterId,
  9. EnumObjectManagerObjects,
  10. type TicketCreateInput,
  11. } from '@shared/graphql/types'
  12. import { useMultiStepForm, useForm } from '@shared/components/Form'
  13. import { useApplicationStore } from '@shared/stores/application'
  14. import { useTicketCreate } from '@shared/entities/ticket/composables/useTicketCreate'
  15. import { useTicketCreateArticleType } from '@shared/entities/ticket/composables/useTicketCreateArticleType'
  16. import { useTicketFormOganizationHandler } from '@shared/entities/ticket/composables/useTicketFormOrganizationHandler'
  17. import { FormData, type FormSchemaNode } from '@shared/components/Form/types'
  18. import { i18n } from '@shared/i18n'
  19. import { MutationHandler } from '@shared/server/apollo/handler'
  20. import { useObjectAttributes } from '@shared/entities/object-attributes/composables/useObjectAttributes'
  21. import { useObjectAttributeFormData } from '@shared/entities/object-attributes/composables/useObjectAttributeFormData'
  22. import {
  23. NotificationTypes,
  24. useNotifications,
  25. } from '@shared/components/CommonNotifications'
  26. import { ErrorStatusCodes } from '@shared/types/error'
  27. import type UserError from '@shared/errors/UserError'
  28. import { defineFormSchema } from '@mobile/form/defineFormSchema'
  29. import { populateEditorNewLines } from '@shared/components/Form/fields/FieldEditor/utils'
  30. import CommonStepper from '@mobile/components/CommonStepper/CommonStepper.vue'
  31. import CommonButton from '@mobile/components/CommonButton/CommonButton.vue'
  32. import CommonBackButton from '@mobile/components/CommonBackButton/CommonBackButton.vue'
  33. // No usage of "type" because of: https://github.com/typescript-eslint/typescript-eslint/issues/5468
  34. import { errorOptions } from '@mobile/router/error'
  35. import useConfirmation from '@mobile/components/CommonConfirmation/composable'
  36. import { useTicketSignature } from '@shared/composables/useTicketSignature'
  37. import { TicketFormData } from '@shared/entities/ticket/types'
  38. import { convertFilesToAttachmentInput } from '@shared/utils/files'
  39. import { useStickyHeader } from '@shared/composables/useStickyHeader'
  40. import { useTicketCreateMutation } from '../graphql/mutations/create.api'
  41. const router = useRouter()
  42. // Add meta header with selected ticket create article type
  43. const { canSubmit, form, node, isDirty, formSubmit } = useForm()
  44. const {
  45. multiStepPlugin,
  46. setMultiStep,
  47. allSteps,
  48. activeStep,
  49. visitedSteps,
  50. stepNames,
  51. lastStepName,
  52. } = useMultiStepForm(node)
  53. const application = useApplicationStore()
  54. const onSubmit = () => {
  55. setMultiStep()
  56. }
  57. const { ticketCreateArticleType, ticketArticleSenderTypeField } =
  58. useTicketCreateArticleType({ onSubmit })
  59. const { isTicketCustomer } = useTicketCreate()
  60. const getFormSchemaGroupSection = (
  61. stepName: string,
  62. sectionTitle: string,
  63. childrens: FormSchemaNode[],
  64. itemsCenter = false,
  65. ) => {
  66. return {
  67. isLayout: true,
  68. element: 'section',
  69. attrs: {
  70. style: {
  71. if: `$activeStep !== "${stepName}"`,
  72. then: 'display: none;',
  73. },
  74. class: {
  75. 'flex flex-col h-full min-h-[calc(100vh_-_15rem)]': true,
  76. 'items-center': itemsCenter,
  77. },
  78. },
  79. children: [
  80. {
  81. type: 'group',
  82. name: stepName,
  83. isGroupOrList: true,
  84. plugins: [multiStepPlugin],
  85. children: [
  86. {
  87. isLayout: true,
  88. element: 'h4',
  89. attrs: {
  90. class: 'my-10 text-base text-center',
  91. },
  92. children: i18n.t(sectionTitle),
  93. },
  94. ...childrens,
  95. ],
  96. },
  97. ],
  98. }
  99. }
  100. const ticketTitleSection = getFormSchemaGroupSection(
  101. 'ticketTitle',
  102. __('Set a title for your ticket'),
  103. [
  104. {
  105. name: 'title',
  106. required: true,
  107. object: EnumObjectManagerObjects.Ticket,
  108. screen: 'create_top',
  109. outerClass:
  110. '$reset formkit-outer w-full grow justify-center flex items-center flex-col',
  111. wrapperClass: '$reset flex w-full',
  112. labelClass: '$reset sr-only',
  113. blockClass: '$reset flex w-full',
  114. innerClass: '$reset flex justify-center items-center px-8 w-full',
  115. messagesClass: 'pt-2',
  116. inputClass:
  117. '$reset formkit-input block bg-transparent grow border-b-[0.5px] border-white outline-none text-center text-xl placeholder:text-white placeholder:text-opacity-50',
  118. props: {
  119. placeholder: __('Title'),
  120. onSubmit,
  121. },
  122. },
  123. ],
  124. true,
  125. )
  126. const ticketArticleTypeSection = getFormSchemaGroupSection(
  127. 'ticketArticleType',
  128. __('Select the type of ticket your are creating'),
  129. [
  130. {
  131. ...ticketArticleSenderTypeField,
  132. outerClass: 'w-full flex grow items-center',
  133. fieldsetClass: 'grow px-4',
  134. },
  135. {
  136. if: '$existingAdditionalCreateNotes() && $getAdditionalCreateNote($values.articleSenderType) !== undefined',
  137. isLayout: true,
  138. element: 'p',
  139. attrs: {
  140. // TODO: check styling for this hint
  141. class: 'my-10 text-base text-center text-yellow',
  142. },
  143. children: '$getAdditionalCreateNote($values.articleSenderType)',
  144. },
  145. ],
  146. true,
  147. )
  148. const ticketMetaInformationSection = getFormSchemaGroupSection(
  149. 'ticketMetaInformation',
  150. __('Additional information'),
  151. [
  152. {
  153. isLayout: true,
  154. component: 'FormGroup',
  155. children: [
  156. {
  157. screen: 'create_top',
  158. object: EnumObjectManagerObjects.Ticket,
  159. },
  160. // Because of the current field screen settings in the backend
  161. // seed we need to add this manually.
  162. {
  163. if: '$values.articleSenderType === "email-out"',
  164. name: 'cc',
  165. label: __('CC'),
  166. type: 'recipient',
  167. props: {
  168. multiple: true,
  169. },
  170. },
  171. ],
  172. },
  173. {
  174. isLayout: true,
  175. component: 'FormGroup',
  176. children: [
  177. {
  178. screen: 'create_middle',
  179. object: EnumObjectManagerObjects.Ticket,
  180. },
  181. ],
  182. },
  183. {
  184. isLayout: true,
  185. component: 'FormGroup',
  186. children: [
  187. {
  188. screen: 'create_bottom',
  189. object: EnumObjectManagerObjects.Ticket,
  190. },
  191. ],
  192. },
  193. ],
  194. )
  195. const ticketArticleMessageSection = getFormSchemaGroupSection(
  196. 'ticketArticleMessage',
  197. __('Add a message'),
  198. [
  199. {
  200. isLayout: true,
  201. component: 'FormGroup',
  202. children: [
  203. {
  204. if: '$smimeIntegration === true && $values.articleSenderType === "email-out"',
  205. name: 'security',
  206. label: __('Security'),
  207. type: 'security',
  208. },
  209. {
  210. name: 'body',
  211. screen: 'create_top',
  212. object: EnumObjectManagerObjects.TicketArticle,
  213. props: {
  214. meta: {
  215. mentionUser: {
  216. groupNodeId: 'group_id',
  217. },
  218. mentionKnowledgeBase: {
  219. attachmentsNodeId: 'attachments',
  220. },
  221. },
  222. },
  223. triggerFormUpdater: false,
  224. },
  225. ],
  226. },
  227. {
  228. isLayout: true,
  229. component: 'FormGroup',
  230. children: [
  231. {
  232. type: 'file',
  233. name: 'attachments',
  234. props: {
  235. multiple: true,
  236. },
  237. },
  238. ],
  239. },
  240. ],
  241. )
  242. const customerSchema = [
  243. ticketTitleSection,
  244. ticketMetaInformationSection,
  245. ticketArticleMessageSection,
  246. ]
  247. const agentSchema = [
  248. ticketTitleSection,
  249. ticketArticleTypeSection,
  250. ticketMetaInformationSection,
  251. ticketArticleMessageSection,
  252. ]
  253. const formSchema = defineFormSchema(
  254. isTicketCustomer.value ? customerSchema : agentSchema,
  255. )
  256. const ticketCreateMutation = new MutationHandler(useTicketCreateMutation({}), {
  257. errorNotificationMessage: __('Ticket could not be created.'),
  258. })
  259. const redirectAfterCreate = (internalId?: number) => {
  260. if (internalId) {
  261. router.replace(`/tickets/${internalId}`)
  262. } else {
  263. router.replace({ name: 'Home' })
  264. }
  265. }
  266. const smimeIntegration = computed(
  267. () => (application.config.smime_integration as boolean) || {},
  268. )
  269. const createTicket = async (formData: FormData<TicketFormData>) => {
  270. const { notify } = useNotifications()
  271. const { attributesLookup: ticketObjectAttributesLookup } =
  272. useObjectAttributes(EnumObjectManagerObjects.Ticket)
  273. const { internalObjectAttributeValues, additionalObjectAttributeValues } =
  274. useObjectAttributeFormData(ticketObjectAttributesLookup.value, formData)
  275. const input = {
  276. ...internalObjectAttributeValues,
  277. article: {
  278. cc: formData.cc,
  279. body: populateEditorNewLines(formData.body),
  280. sender: isTicketCustomer.value
  281. ? 'Customer'
  282. : ticketCreateArticleType[formData.articleSenderType].sender,
  283. type: isTicketCustomer.value
  284. ? 'web'
  285. : ticketCreateArticleType[formData.articleSenderType].type,
  286. contentType: 'text/html',
  287. security: formData.security,
  288. },
  289. objectAttributeValues: additionalObjectAttributeValues,
  290. } as TicketCreateInput
  291. if (formData.attachments && input.article) {
  292. input.article.attachments = convertFilesToAttachmentInput(
  293. formData.formId,
  294. formData.attachments,
  295. )
  296. }
  297. return ticketCreateMutation
  298. .send({ input })
  299. .then((result) => {
  300. if (result?.ticketCreate?.ticket) {
  301. notify({
  302. type: NotificationTypes.Success,
  303. message: __('Ticket has been created successfully.'),
  304. })
  305. return () => {
  306. const ticket = result.ticketCreate?.ticket
  307. redirectAfterCreate(
  308. ticket?.policy.update ? ticket.internalId : undefined,
  309. )
  310. }
  311. }
  312. return null
  313. })
  314. .catch((errors: UserError) => {
  315. notify({
  316. message: errors.generalErrors[0],
  317. type: NotificationTypes.Error,
  318. })
  319. })
  320. }
  321. const additionalCreateNotes = computed(
  322. () =>
  323. (application.config.ui_ticket_create_notes as Record<string, string>) || {},
  324. )
  325. const schemaData = reactive({
  326. activeStep,
  327. visitedSteps,
  328. allSteps,
  329. smimeIntegration,
  330. existingAdditionalCreateNotes: () => {
  331. return Object.keys(additionalCreateNotes).length > 0
  332. },
  333. getAdditionalCreateNote: (value: string) => {
  334. return i18n.t(additionalCreateNotes.value[value])
  335. },
  336. })
  337. const submitButtonDisabled = computed(() => {
  338. return (
  339. !canSubmit.value ||
  340. (activeStep.value !== lastStepName.value &&
  341. visitedSteps.value.length < stepNames.value.length)
  342. )
  343. })
  344. const moveStep = () => {
  345. if (activeStep.value === lastStepName.value) {
  346. formSubmit()
  347. return
  348. }
  349. setMultiStep()
  350. }
  351. const { stickyStyles, headerElement } = useStickyHeader()
  352. const bodyElement = ref<HTMLElement>()
  353. const isScrolledToBottom = ref(true)
  354. const setIsScrolledToBottom = () => {
  355. isScrolledToBottom.value =
  356. window.innerHeight +
  357. document.documentElement.scrollTop -
  358. (headerElement.value?.clientHeight || 0) >=
  359. (bodyElement.value?.scrollHeight || 0)
  360. }
  361. watch(
  362. () => activeStep.value,
  363. () => {
  364. nextTick(() => {
  365. setIsScrolledToBottom()
  366. })
  367. },
  368. )
  369. useEventListener('scroll', setIsScrolledToBottom)
  370. useEventListener('resize', setIsScrolledToBottom)
  371. const { waitForConfirmation } = useConfirmation()
  372. onBeforeRouteLeave(async () => {
  373. if (!isDirty.value) return true
  374. const confirmed = await waitForConfirmation(
  375. __('Are you sure? You have unsaved changes that will get lost.'),
  376. {
  377. buttonTitle: __('Discard changes'),
  378. buttonVariant: 'danger',
  379. },
  380. )
  381. return confirmed
  382. })
  383. const { signatureHandling } = useTicketSignature()
  384. </script>
  385. <script lang="ts">
  386. export default {
  387. beforeRouteEnter(to, from, next) {
  388. const { ticketCreateEnabled } = useTicketCreate()
  389. if (!ticketCreateEnabled.value) {
  390. errorOptions.value = {
  391. title: __('Forbidden'),
  392. message: __('Creating new tickets via web is disabled.'),
  393. statusCode: ErrorStatusCodes.Forbidden,
  394. route: to.fullPath,
  395. }
  396. next({
  397. name: 'Error',
  398. query: {
  399. redirect: '1',
  400. },
  401. replace: true,
  402. })
  403. return
  404. }
  405. next()
  406. },
  407. }
  408. </script>
  409. <template>
  410. <header
  411. ref="headerElement"
  412. :style="stickyStyles.header"
  413. class="border-b-[0.5px] border-white/10 bg-black px-4"
  414. >
  415. <div class="grid h-16 grid-cols-[75px_auto_75px]">
  416. <div
  417. class="flex cursor-pointer items-center justify-self-start text-base"
  418. >
  419. <CommonBackButton fallback="/" />
  420. </div>
  421. <h1
  422. class="flex flex-1 items-center justify-center text-center text-lg font-bold"
  423. >
  424. {{ $t('Create Ticket') }}
  425. </h1>
  426. <div class="flex items-center justify-self-end text-base">
  427. <CommonButton
  428. variant="submit"
  429. :disabled="submitButtonDisabled"
  430. transparent-background
  431. @click="formSubmit"
  432. >
  433. {{ $t('Create') }}
  434. </CommonButton>
  435. </div>
  436. </div>
  437. </header>
  438. <div
  439. ref="bodyElement"
  440. :style="stickyStyles.body"
  441. class="flex h-full flex-col px-4"
  442. >
  443. <Form
  444. id="ticket-create"
  445. ref="form"
  446. class="pb-32 text-left"
  447. :schema="formSchema"
  448. :handlers="[useTicketFormOganizationHandler(), signatureHandling('body')]"
  449. :flatten-form-groups="Object.keys(allSteps)"
  450. :schema-data="schemaData"
  451. :form-updater-id="EnumFormUpdaterId.FormUpdaterUpdaterTicketCreate"
  452. :autofocus="true"
  453. use-object-attributes
  454. @submit="createTicket($event as FormData<TicketFormData>)"
  455. />
  456. </div>
  457. <footer
  458. :class="{
  459. 'bg-gray-light backdrop-blur-lg': !isScrolledToBottom,
  460. }"
  461. class="bottom-navigation fixed bottom-0 z-10 h-32 w-full px-4 transition"
  462. >
  463. <FormKit
  464. :variant="lastStepName === activeStep ? 'submit' : 'primary'"
  465. type="button"
  466. outer-class="mt-4 mb-2"
  467. :disabled="lastStepName === activeStep && submitButtonDisabled"
  468. wrapper-class="flex grow justify-center items-center"
  469. input-class="py-2 px-4 w-full h-14 text-lg rounded-xl select-none"
  470. @click="moveStep()"
  471. >
  472. {{ lastStepName === activeStep ? $t('Create ticket') : $t('Continue') }}
  473. </FormKit>
  474. <CommonStepper
  475. v-model="activeStep"
  476. :steps="allSteps"
  477. class="mt-4 mb-8 px-8"
  478. />
  479. </footer>
  480. </template>