tickets_controller.rb 21 KB

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