TicketCreate.vue 14 KB

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