tickets_controller.rb 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. # permit nested conditions
  387. if params[:condition]
  388. params.require(:condition).permit!
  389. end
  390. paginate_with(max: 200, default: 50)
  391. query = params[:query]
  392. if query.respond_to?(:permit!)
  393. query = query.permit!.to_h
  394. end
  395. # build result list
  396. tickets = Ticket.search(
  397. query: query,
  398. condition: params[:condition].to_h,
  399. limit: pagination.limit,
  400. offset: pagination.offset,
  401. order_by: params[:order_by],
  402. sort_by: params[:sort_by],
  403. current_user: current_user,
  404. )
  405. if response_expand?
  406. list = tickets.map(&:attributes_with_association_names)
  407. render json: list, status: :ok
  408. return
  409. end
  410. assets = {}
  411. ticket_result = []
  412. tickets.each do |ticket|
  413. ticket_result.push ticket.id
  414. assets = ticket.assets(assets)
  415. end
  416. # return result
  417. render json: {
  418. tickets: ticket_result,
  419. tickets_count: tickets.count,
  420. assets: assets,
  421. }
  422. end
  423. # GET /api/v1/ticket_stats
  424. def stats
  425. if !params[:user_id] && !params[:organization_id]
  426. raise __('Need user_id or organization_id as param')
  427. end
  428. # lookup open user tickets
  429. limit = 100
  430. assets = {}
  431. user_tickets = {}
  432. if params[:user_id]
  433. user = User.lookup(id: params[:user_id])
  434. if !user
  435. raise "No such user with id #{params[:user_id]}"
  436. end
  437. conditions = {
  438. closed_ids: {
  439. 'ticket.state_id' => {
  440. operator: 'is',
  441. value: Ticket::State.by_category_ids(:closed),
  442. },
  443. 'ticket.customer_id' => {
  444. operator: 'is',
  445. value: user.id,
  446. },
  447. },
  448. open_ids: {
  449. 'ticket.state_id' => {
  450. operator: 'is',
  451. value: Ticket::State.by_category_ids(:open),
  452. },
  453. 'ticket.customer_id' => {
  454. operator: 'is',
  455. value: user.id,
  456. },
  457. },
  458. }
  459. conditions.each do |key, local_condition|
  460. user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  461. end
  462. # generate stats by user
  463. condition = {
  464. 'tickets.customer_id' => user.id,
  465. }
  466. user_tickets[:volume_by_year] = ticket_stats_last_year(condition)
  467. end
  468. # lookup open org tickets
  469. org_tickets = {}
  470. organization_ids = Array(params[:organization_id])
  471. if organization_ids.present?
  472. organization_ids.each do |organization_id|
  473. organization = Organization.lookup(id: organization_id)
  474. if !organization
  475. raise "No such organization with id #{organization_id}"
  476. end
  477. end
  478. conditions = {
  479. closed_ids: {
  480. 'ticket.state_id' => {
  481. operator: 'is',
  482. value: Ticket::State.by_category_ids(:closed),
  483. },
  484. 'ticket.organization_id' => {
  485. operator: 'is',
  486. value: organization_ids,
  487. },
  488. },
  489. open_ids: {
  490. 'ticket.state_id' => {
  491. operator: 'is',
  492. value: Ticket::State.by_category_ids(:open),
  493. },
  494. 'ticket.organization_id' => {
  495. operator: 'is',
  496. value: organization_ids,
  497. },
  498. },
  499. }
  500. conditions.each do |key, local_condition|
  501. org_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  502. end
  503. # generate stats by org
  504. condition = {
  505. 'tickets.organization_id' => organization_ids,
  506. }
  507. org_tickets[:volume_by_year] = ticket_stats_last_year(condition)
  508. end
  509. # return result
  510. render json: {
  511. user: user_tickets,
  512. organization: org_tickets,
  513. assets: assets,
  514. }
  515. end
  516. # @path [GET] /tickets/import_example
  517. #
  518. # @summary Download of example CSV file.
  519. # @notes The requester have 'admin' permissions to be able to download it.
  520. # @example curl -u #{login}:#{password} http://localhost:3000/api/v1/tickets/import_example
  521. #
  522. # @response_message 200 File download.
  523. # @response_message 403 Forbidden / Invalid session.
  524. def import_example
  525. csv_string = Ticket.csv_example(
  526. col_sep: ',',
  527. )
  528. send_data(
  529. csv_string,
  530. filename: 'example.csv',
  531. type: 'text/csv',
  532. disposition: 'attachment'
  533. )
  534. end
  535. # @path [POST] /tickets/import
  536. #
  537. # @summary Starts import.
  538. # @notes The requester have 'admin' permissions to be create a new import.
  539. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import?try=true'
  540. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import'
  541. #
  542. # @response_message 201 Import started.
  543. # @response_message 403 Forbidden / Invalid session.
  544. def import_start
  545. if Setting.get('import_mode') != true
  546. raise __('Tickets can only be imported if system is in import mode.')
  547. end
  548. string = params[:data]
  549. if string.blank? && params[:file].present?
  550. string = params[:file].read.force_encoding('utf-8')
  551. end
  552. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  553. result = Ticket.csv_import(
  554. string: string,
  555. parse_params: {
  556. col_sep: params[:col_sep] || ',',
  557. },
  558. try: params[:try],
  559. )
  560. render json: result, status: :ok
  561. end
  562. private
  563. def ticket_all(ticket)
  564. # get attributes to update
  565. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  566. current_user: current_user,
  567. ticket: ticket,
  568. screen: 'edit',
  569. )
  570. # get related users
  571. assets = attributes_to_change[:assets]
  572. assets = ticket.assets(assets)
  573. # get related users
  574. article_ids = []
  575. ticket.articles.each do |article|
  576. next if !authorized?(article, :show?)
  577. article_ids.push article.id
  578. assets = article.assets(assets)
  579. end
  580. # get links
  581. links = Link.list(
  582. link_object: 'Ticket',
  583. link_object_value: ticket.id,
  584. user: current_user,
  585. )
  586. assets = Link.reduce_assets(assets, links)
  587. # get tags
  588. tags = ticket.tag_list
  589. # get time units
  590. time_accountings = ticket.ticket_time_accounting.map { |row| row.slice(:id, :ticket_id, :ticket_article_id, :time_unit, :type_id) }
  591. # get mentions
  592. mentions = Mention.where(mentionable: ticket).reorder(created_at: :desc)
  593. mentions.each do |mention|
  594. assets = mention.assets(assets)
  595. end
  596. if (draft = ticket.shared_draft) && authorized?(draft, :show?)
  597. assets = draft.assets(assets)
  598. end
  599. if Setting.get('checklist') && current_user.permissions?('ticket.agent')
  600. ticket.checklist&.assets(assets)
  601. ticket.referencing_checklists
  602. .includes(:ticket)
  603. .each do |elem|
  604. elem.assets(assets)
  605. elem.ticket.assets(assets) if elem.ticket.authorized_asset?
  606. end
  607. end
  608. # return result
  609. {
  610. ticket_id: ticket.id,
  611. ticket_article_ids: article_ids,
  612. assets: assets,
  613. links: links,
  614. tags: tags,
  615. mentions: mentions.pluck(:id),
  616. time_accountings: time_accountings,
  617. form_meta: attributes_to_change[:form_meta],
  618. }
  619. end
  620. end