tickets_controller.rb 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class TicketsController < ApplicationController
  3. include CreatesTicketArticles
  4. include ClonesTicketArticleAttachments
  5. include ChecksUserAttributesByCurrentUserPermission
  6. include TicketStats
  7. include CanPaginate
  8. prepend_before_action -> { authorize! }, only: %i[create import_example import_start ticket_customer ticket_history ticket_related ticket_recent ticket_merge ticket_split]
  9. prepend_before_action :authentication_check
  10. # GET /api/v1/tickets
  11. def index
  12. paginate_with(max: 100)
  13. tickets = TicketPolicy::ReadScope.new(current_user).resolve
  14. .reorder(id: :asc)
  15. .offset(pagination.offset)
  16. .limit(pagination.limit)
  17. if response_expand?
  18. list = tickets.map(&:attributes_with_association_names)
  19. render json: list, status: :ok
  20. return
  21. end
  22. if response_full?
  23. assets = {}
  24. item_ids = []
  25. tickets.each do |item|
  26. item_ids.push item.id
  27. assets = item.assets(assets)
  28. end
  29. render json: {
  30. record_ids: item_ids,
  31. assets: assets,
  32. }, status: :ok
  33. return
  34. end
  35. render json: tickets
  36. end
  37. # GET /api/v1/tickets/1
  38. def show
  39. ticket = Ticket.find(params[:id])
  40. authorize!(ticket)
  41. auto_assign_ticket(ticket)
  42. if response_expand?
  43. result = ticket.attributes_with_association_names
  44. render json: result, status: :ok
  45. return
  46. end
  47. if response_full?
  48. full = Ticket.full(params[:id])
  49. render json: full
  50. return
  51. end
  52. if response_all?
  53. render json: ticket_all(ticket)
  54. return
  55. end
  56. render json: ticket
  57. end
  58. def auto_assign_ticket(ticket)
  59. return if params[:auto_assign].blank?
  60. ticket.auto_assign(current_user)
  61. end
  62. # POST /api/v1/tickets
  63. def create
  64. ticket = nil
  65. Transaction.execute do # rubocop:disable Metrics/BlockLength
  66. customer = {}
  67. if params[:customer].instance_of?(ActionController::Parameters)
  68. customer = params[:customer]
  69. params.delete(:customer)
  70. end
  71. if (shared_draft_id = params[:shared_draft_id])
  72. shared_draft = Ticket::SharedDraftStart.find_by id: shared_draft_id
  73. if shared_draft && (shared_draft.group_id.to_s != params[:group_id]&.to_s || !shared_draft.group.shared_drafts?)
  74. raise Exceptions::UnprocessableEntity, __('Shared draft cannot be selected for this ticket.')
  75. end
  76. shared_draft&.destroy
  77. end
  78. # Prevent direct access to checklist via API
  79. # Otherwise users may get unauthorized access to checklists of other tickets
  80. params.delete(:checklist)
  81. params.delete(:checklist_id)
  82. clean_params = Ticket.association_name_to_id_convert(params)
  83. # overwrite params
  84. if !current_user.permissions?('ticket.agent')
  85. %i[owner owner_id customer customer_id preferences].each do |key|
  86. clean_params.delete(key)
  87. end
  88. clean_params[:customer_id] = current_user.id
  89. end
  90. # The parameter :customer_id is 'abused' in cases where it is not an integer, but a string like
  91. # 'guess:customers.email@domain.cm' which implies that the customer should be looked up.
  92. if clean_params[:customer_id].is_a?(String) && clean_params[:customer_id] =~ %r{^guess:(.+?)$}
  93. email_address = $1
  94. email_address_validation = EmailAddressValidation.new(email_address)
  95. if !email_address_validation.valid?
  96. render json: { error: "Invalid email '#{email_address}' of customer" }, status: :unprocessable_entity
  97. return
  98. end
  99. local_customer = User.find_by(email: email_address.downcase)
  100. if !local_customer
  101. role_ids = Role.signup_role_ids
  102. local_customer = User.create(
  103. firstname: '',
  104. lastname: '',
  105. email: email_address,
  106. password: '',
  107. active: true,
  108. role_ids: role_ids,
  109. )
  110. end
  111. clean_params[:customer_id] = local_customer.id
  112. end
  113. # try to create customer if needed
  114. if clean_params[:customer_id].blank? && customer.present?
  115. check_attributes_by_current_user_permission(customer)
  116. clean_customer = User.association_name_to_id_convert(customer)
  117. local_customer = nil
  118. if !local_customer && clean_customer[:id].present?
  119. local_customer = User.find_by(id: clean_customer[:id])
  120. end
  121. if !local_customer && clean_customer[:email].present?
  122. local_customer = User.find_by(email: clean_customer[:email].downcase)
  123. end
  124. if !local_customer && clean_customer[:login].present?
  125. local_customer = User.find_by(login: clean_customer[:login].downcase)
  126. end
  127. if !local_customer
  128. role_ids = Role.signup_role_ids
  129. local_customer = User.new(clean_customer)
  130. local_customer.role_ids = role_ids
  131. local_customer.save!
  132. end
  133. clean_params[:customer_id] = local_customer.id
  134. end
  135. clean_params = Ticket.param_cleanup(clean_params, true)
  136. clean_params[:screen] = 'create_middle'
  137. ticket = Ticket.new(clean_params)
  138. authorize!(ticket, :create?)
  139. # create ticket
  140. ticket.save!
  141. # create tags if given
  142. if params[:tags].present?
  143. tags = params[:tags].split(',').map(&:strip)
  144. tags.each do |tag|
  145. next if !::Tag.tag_allowed?(name: tag, user_id: UserInfo.current_user_id)
  146. ticket.tag_add(tag)
  147. end
  148. end
  149. # This mentions handling is used by custom API calls only
  150. # Mentions created in UI are handled by Ticket::Article#check_mentions
  151. if params[:mentions].present?
  152. authorize!(ticket, :create_mentions?)
  153. Array(params[:mentions]).each do |user_id|
  154. Mention.subscribe! ticket, User.find(user_id)
  155. end
  156. end
  157. # create article if given
  158. if params[:article]
  159. article_create(ticket, params[:article])
  160. end
  161. # create links (e. g. in case of ticket split)
  162. # links: {
  163. # Ticket: {
  164. # parent: [ticket_id1, ticket_id2, ...]
  165. # normal: [ticket_id1, ticket_id2, ...]
  166. # child: [ticket_id1, ticket_id2, ...]
  167. # },
  168. # }
  169. if params[:links].present?
  170. link = params[:links].permit!.to_h
  171. raise Exceptions::UnprocessableEntity, __('Invalid link structure') if !link.is_a? Hash
  172. link.each do |target_object, link_types_with_object_ids|
  173. raise Exceptions::UnprocessableEntity, __('Invalid link structure (Object)') if !link_types_with_object_ids.is_a? Hash
  174. link_types_with_object_ids.each do |link_type, object_ids|
  175. raise Exceptions::UnprocessableEntity, __('Invalid link structure (Object → LinkType)') if !object_ids.is_a? Array
  176. object_ids.each do |local_object_id|
  177. link = Link.add(
  178. link_type: link_type,
  179. link_object_target: target_object,
  180. link_object_target_value: local_object_id,
  181. link_object_source: 'Ticket',
  182. link_object_source_value: ticket.id,
  183. )
  184. end
  185. end
  186. end
  187. end
  188. end
  189. if response_expand?
  190. result = ticket.reload.attributes_with_association_names
  191. render json: result, status: :created
  192. return
  193. end
  194. if response_full?
  195. full = Ticket.full(ticket.id)
  196. render json: full, status: :created
  197. return
  198. end
  199. if response_all?
  200. render json: ticket_all(ticket.reload), status: :created
  201. return
  202. end
  203. render json: ticket.reload.attributes_with_association_ids, status: :created
  204. end
  205. # PUT /api/v1/tickets/1
  206. def update
  207. ticket = Ticket.find(params[:id])
  208. authorize!(ticket, :follow_up?)
  209. # Prevent direct access to checklist via API
  210. # Otherwise users may get unauthorized access to checklists of other tickets
  211. params.delete(:checklist)
  212. params.delete(:checklist_id)
  213. clean_params = Ticket.association_name_to_id_convert(params)
  214. clean_params = Ticket.param_cleanup(clean_params, true)
  215. # only apply preferences changes (keep not updated keys/values)
  216. clean_params = ticket.param_preferences_merge(clean_params)
  217. clean_params[:screen] = 'edit'
  218. # disable changes on ticket number
  219. clean_params.delete('number')
  220. # overwrite params
  221. if !current_user.permissions?('ticket.agent')
  222. %i[owner owner_id customer customer_id organization organization_id preferences].each do |key|
  223. clean_params.delete(key)
  224. end
  225. end
  226. ticket.with_lock do
  227. ticket.update!(clean_params)
  228. if params[:article].present?
  229. if (shared_draft_id = params[:article][:shared_draft_id])
  230. shared_draft = Ticket::SharedDraftZoom.find_by id: shared_draft_id
  231. if shared_draft && shared_draft.ticket != ticket
  232. raise Exceptions::UnprocessableEntity, __('Shared draft cannot be selected for this ticket.')
  233. end
  234. shared_draft&.destroy
  235. end
  236. article_create(ticket, params[:article])
  237. end
  238. end
  239. if response_expand?
  240. result = ticket.reload.attributes_with_association_names
  241. render json: result, status: :ok
  242. return
  243. end
  244. if response_full?
  245. full = Ticket.full(params[:id])
  246. render json: full, status: :ok
  247. return
  248. end
  249. if response_all?
  250. render json: ticket_all(ticket.reload), status: :ok
  251. return
  252. end
  253. render json: ticket.reload.attributes_with_association_ids, status: :ok
  254. end
  255. # DELETE /api/v1/tickets/1
  256. def destroy
  257. ticket = Ticket.find(params[:id])
  258. authorize!(ticket)
  259. ticket.destroy!
  260. head :ok
  261. end
  262. # GET /api/v1/ticket_customer
  263. # GET /api/v1/tickets_customer
  264. def ticket_customer
  265. # return result
  266. result = Ticket::ScreenOptions.list_by_customer(
  267. current_user: current_user,
  268. customer_id: params[:customer_id],
  269. limit: 15,
  270. )
  271. render json: result
  272. end
  273. # GET /api/v1/ticket_history/1
  274. def ticket_history
  275. # get ticket data
  276. ticket = Ticket.find(params[:id])
  277. authorize!(ticket, :show?)
  278. # get history of ticket
  279. render json: ticket.history_get(true)
  280. end
  281. # GET /api/v1/ticket_related/1
  282. def ticket_related
  283. ticket = Ticket.find(params[:ticket_id])
  284. assets = ticket.assets({})
  285. tickets = TicketPolicy::ReadScope.new(current_user).resolve
  286. .where(
  287. customer_id: ticket.customer_id,
  288. state_id: Ticket::State.by_category(:open).select(:id),
  289. )
  290. .where.not(id: ticket.id)
  291. .reorder(created_at: :desc)
  292. .limit(6)
  293. # if we do not have open related tickets, search for any tickets
  294. tickets ||= TicketPolicy::ReadScope.new(current_user).resolve
  295. .where(customer_id: ticket.customer_id)
  296. .where.not(state_id: Ticket::State.by_category_ids(:merged))
  297. .where.not(id: ticket.id)
  298. .reorder(created_at: :desc)
  299. .limit(6)
  300. # get related assets
  301. ticket_ids_by_customer = []
  302. tickets.each do |ticket_list|
  303. ticket_ids_by_customer.push ticket_list.id
  304. assets = ticket_list.assets(assets)
  305. end
  306. ticket_ids_recent_viewed = []
  307. recent_views = RecentView.list(current_user, 8, 'Ticket')
  308. recent_views.each do |recent_view|
  309. next if recent_view.object.name != 'Ticket'
  310. next if recent_view.o_id == ticket.id
  311. ticket_ids_recent_viewed.push recent_view.o_id
  312. recent_view_ticket = Ticket.find(recent_view.o_id)
  313. assets = recent_view_ticket.assets(assets)
  314. end
  315. # return result
  316. render json: {
  317. assets: assets,
  318. ticket_ids_by_customer: ticket_ids_by_customer,
  319. ticket_ids_recent_viewed: ticket_ids_recent_viewed,
  320. }
  321. end
  322. # GET /api/v1/ticket_recent
  323. def ticket_recent
  324. ticket_ids = RecentView.list(current_user, 10, Ticket.name).map(&:o_id)
  325. tickets = ticket_ids.map { |elem| Ticket.lookup(id: elem) }
  326. assets = ApplicationModel::CanAssets.reduce(tickets)
  327. render json: {
  328. assets: assets,
  329. ticket_ids_recent_viewed: ticket_ids
  330. }
  331. end
  332. # PUT /api/v1/ticket_merge/1/1
  333. def ticket_merge
  334. # check target ticket
  335. target_ticket = Ticket.find_by(number: params[:target_ticket_number])
  336. if !target_ticket
  337. render json: {
  338. result: 'failed',
  339. message: __('The target ticket number could not be found.'),
  340. }
  341. return
  342. end
  343. # check source ticket
  344. source_ticket = Ticket.find_by(id: params[:source_ticket_id])
  345. if !source_ticket
  346. render json: {
  347. result: 'failed',
  348. message: __('The source ticket could not be found.'),
  349. }
  350. return
  351. end
  352. # merge ticket
  353. Service::Ticket::Merge.new(current_user:).execute(source_ticket:, target_ticket:)
  354. # return result
  355. render json: {
  356. result: 'success',
  357. target_ticket: target_ticket.attributes,
  358. source_ticket: source_ticket.attributes,
  359. }
  360. end
  361. # GET /api/v1/ticket_split
  362. def ticket_split
  363. ticket = Ticket.find(params[:ticket_id])
  364. authorize!(ticket, :show?)
  365. assets = ticket.assets({})
  366. article = Ticket::Article.find(params[:article_id])
  367. authorize!(article.ticket, :show?)
  368. assets = article.assets(assets)
  369. render json: {
  370. assets: assets,
  371. attachments: article_attachments_clone(article),
  372. }
  373. end
  374. # GET /api/v1/ticket_create
  375. def ticket_create
  376. # get attributes to update
  377. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  378. view: 'ticket_create',
  379. screen: 'create_middle',
  380. current_user: current_user,
  381. )
  382. render json: attributes_to_change
  383. end
  384. # GET /api/v1/tickets/search
  385. def search
  386. model_search_render(Ticket, params)
  387. end
  388. # GET /api/v1/ticket_stats
  389. def stats
  390. if !params[:user_id] && !params[:organization_id]
  391. raise __('Need user_id or organization_id as param')
  392. end
  393. # lookup open user tickets
  394. limit = 100
  395. assets = {}
  396. user_tickets = {}
  397. if params[:user_id]
  398. user = User.lookup(id: params[:user_id])
  399. if !user
  400. raise "No such user with id #{params[:user_id]}"
  401. end
  402. conditions = {
  403. closed_ids: {
  404. 'ticket.state_id' => {
  405. operator: 'is',
  406. value: Ticket::State.by_category_ids(:closed),
  407. },
  408. 'ticket.customer_id' => {
  409. operator: 'is',
  410. value: user.id,
  411. },
  412. },
  413. open_ids: {
  414. 'ticket.state_id' => {
  415. operator: 'is',
  416. value: Ticket::State.by_category_ids(:open),
  417. },
  418. 'ticket.customer_id' => {
  419. operator: 'is',
  420. value: user.id,
  421. },
  422. },
  423. }
  424. conditions.each do |key, local_condition|
  425. user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  426. end
  427. # generate stats by user
  428. condition = {
  429. 'tickets.customer_id' => user.id,
  430. }
  431. user_tickets[:volume_by_year] = ticket_stats_last_year(condition)
  432. end
  433. # lookup open org tickets
  434. org_tickets = {}
  435. organization_ids = Array(params[:organization_id])
  436. if organization_ids.present?
  437. organization_ids.each do |organization_id|
  438. organization = Organization.lookup(id: organization_id)
  439. if !organization
  440. raise "No such organization with id #{organization_id}"
  441. end
  442. end
  443. conditions = {
  444. closed_ids: {
  445. 'ticket.state_id' => {
  446. operator: 'is',
  447. value: Ticket::State.by_category_ids(:closed),
  448. },
  449. 'ticket.organization_id' => {
  450. operator: 'is',
  451. value: organization_ids,
  452. },
  453. },
  454. open_ids: {
  455. 'ticket.state_id' => {
  456. operator: 'is',
  457. value: Ticket::State.by_category_ids(:open),
  458. },
  459. 'ticket.organization_id' => {
  460. operator: 'is',
  461. value: organization_ids,
  462. },
  463. },
  464. }
  465. conditions.each do |key, local_condition|
  466. org_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  467. end
  468. # generate stats by org
  469. condition = {
  470. 'tickets.organization_id' => organization_ids,
  471. }
  472. org_tickets[:volume_by_year] = ticket_stats_last_year(condition)
  473. end
  474. # return result
  475. render json: {
  476. user: user_tickets,
  477. organization: org_tickets,
  478. assets: assets,
  479. }
  480. end
  481. # @path [GET] /tickets/import_example
  482. #
  483. # @summary Download of example CSV file.
  484. # @notes The requester have 'admin' permissions to be able to download it.
  485. # @example curl -u #{login}:#{password} http://localhost:3000/api/v1/tickets/import_example
  486. #
  487. # @response_message 200 File download.
  488. # @response_message 403 Forbidden / Invalid session.
  489. def import_example
  490. csv_string = Ticket.csv_example(
  491. col_sep: ',',
  492. )
  493. send_data(
  494. csv_string,
  495. filename: 'example.csv',
  496. type: 'text/csv',
  497. disposition: 'attachment'
  498. )
  499. end
  500. # @path [POST] /tickets/import
  501. #
  502. # @summary Starts import.
  503. # @notes The requester have 'admin' permissions to be create a new import.
  504. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import?try=true'
  505. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import'
  506. #
  507. # @response_message 201 Import started.
  508. # @response_message 403 Forbidden / Invalid session.
  509. def import_start
  510. if Setting.get('import_mode') != true
  511. raise __('Tickets can only be imported if system is in import mode.')
  512. end
  513. string = params[:data]
  514. if string.blank? && params[:file].present?
  515. string = params[:file].read.force_encoding('utf-8')
  516. end
  517. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  518. result = Ticket.csv_import(
  519. string: string,
  520. parse_params: {
  521. col_sep: params[:col_sep] || ',',
  522. },
  523. try: params[:try],
  524. )
  525. render json: result, status: :ok
  526. end
  527. private
  528. def ticket_all(ticket)
  529. # get attributes to update
  530. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  531. current_user: current_user,
  532. ticket: ticket,
  533. screen: 'edit',
  534. )
  535. # get related users
  536. assets = attributes_to_change[:assets]
  537. assets = ticket.assets(assets)
  538. # get related users
  539. article_ids = []
  540. ticket.articles.each do |article|
  541. next if !authorized?(article, :show?)
  542. article_ids.push article.id
  543. assets = article.assets(assets)
  544. end
  545. # get links
  546. links = Link.list(
  547. link_object: 'Ticket',
  548. link_object_value: ticket.id,
  549. user: current_user,
  550. )
  551. assets = Link.reduce_assets(assets, links)
  552. # get tags
  553. tags = ticket.tag_list
  554. # get time units
  555. time_accountings = ticket.ticket_time_accounting.map { |row| row.slice(:id, :ticket_id, :ticket_article_id, :time_unit, :type_id) }
  556. # get mentions
  557. mentions = Mention.where(mentionable: ticket).reorder(created_at: :desc)
  558. mentions.each do |mention|
  559. assets = mention.assets(assets)
  560. end
  561. if (draft = ticket.shared_draft) && authorized?(draft, :show?)
  562. assets = draft.assets(assets)
  563. end
  564. if Setting.get('checklist') && current_user.permissions?('ticket.agent')
  565. ticket.checklist&.assets(assets)
  566. ticket.referencing_checklists
  567. .includes(:ticket)
  568. .each do |elem|
  569. elem.assets(assets)
  570. elem.ticket.assets(assets) if elem.ticket.authorized_asset?
  571. end
  572. end
  573. # return result
  574. {
  575. ticket_id: ticket.id,
  576. ticket_article_ids: article_ids,
  577. assets: assets,
  578. links: links,
  579. tags: tags,
  580. mentions: mentions.pluck(:id),
  581. time_accountings: time_accountings,
  582. form_meta: attributes_to_change[:form_meta],
  583. }
  584. end
  585. end