tickets_controller.rb 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 = []
  19. tickets.each do |ticket|
  20. list.push ticket.attributes_with_association_names
  21. end
  22. render json: list, status: :ok
  23. return
  24. end
  25. if response_full?
  26. assets = {}
  27. item_ids = []
  28. tickets.each do |item|
  29. item_ids.push item.id
  30. assets = item.assets(assets)
  31. end
  32. render json: {
  33. record_ids: item_ids,
  34. assets: assets,
  35. }, status: :ok
  36. return
  37. end
  38. render json: tickets
  39. end
  40. # GET /api/v1/tickets/1
  41. def show
  42. ticket = Ticket.find(params[:id])
  43. authorize!(ticket)
  44. auto_assign_ticket(ticket)
  45. if response_expand?
  46. result = ticket.attributes_with_association_names
  47. render json: result, status: :ok
  48. return
  49. end
  50. if response_full?
  51. full = Ticket.full(params[:id])
  52. render json: full
  53. return
  54. end
  55. if response_all?
  56. render json: ticket_all(ticket)
  57. return
  58. end
  59. render json: ticket
  60. end
  61. def auto_assign_ticket(ticket)
  62. return if params[:auto_assign].blank?
  63. ticket.auto_assign(current_user)
  64. end
  65. # POST /api/v1/tickets
  66. def create
  67. ticket = nil
  68. Transaction.execute do # rubocop:disable Metrics/BlockLength
  69. customer = {}
  70. if params[:customer].instance_of?(ActionController::Parameters)
  71. customer = params[:customer]
  72. params.delete(:customer)
  73. end
  74. if (shared_draft_id = params[:shared_draft_id])
  75. shared_draft = Ticket::SharedDraftStart.find_by id: shared_draft_id
  76. if shared_draft && (shared_draft.group_id.to_s != params[:group_id]&.to_s || !shared_draft.group.shared_drafts?)
  77. raise Exceptions::UnprocessableEntity, __('Shared draft cannot be selected for this ticket.')
  78. end
  79. shared_draft&.destroy
  80. end
  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. clean_params = Ticket.association_name_to_id_convert(params)
  209. clean_params = Ticket.param_cleanup(clean_params, true)
  210. # only apply preferences changes (keep not updated keys/values)
  211. clean_params = ticket.param_preferences_merge(clean_params)
  212. clean_params[:screen] = 'edit'
  213. # disable changes on ticket number
  214. clean_params.delete('number')
  215. # overwrite params
  216. if !current_user.permissions?('ticket.agent')
  217. %i[owner owner_id customer customer_id organization organization_id preferences].each do |key|
  218. clean_params.delete(key)
  219. end
  220. end
  221. ticket.with_lock do
  222. ticket.update!(clean_params)
  223. if params[:article].present?
  224. if (shared_draft_id = params[:article][:shared_draft_id])
  225. shared_draft = Ticket::SharedDraftZoom.find_by id: shared_draft_id
  226. if shared_draft && shared_draft.ticket != ticket
  227. raise Exceptions::UnprocessableEntity, __('Shared draft cannot be selected for this ticket.')
  228. end
  229. shared_draft&.destroy
  230. end
  231. article_create(ticket, params[:article])
  232. end
  233. end
  234. if response_expand?
  235. result = ticket.reload.attributes_with_association_names
  236. render json: result, status: :ok
  237. return
  238. end
  239. if response_full?
  240. full = Ticket.full(params[:id])
  241. render json: full, status: :ok
  242. return
  243. end
  244. if response_all?
  245. render json: ticket_all(ticket.reload), status: :ok
  246. return
  247. end
  248. render json: ticket.reload.attributes_with_association_ids, status: :ok
  249. end
  250. # DELETE /api/v1/tickets/1
  251. def destroy
  252. ticket = Ticket.find(params[:id])
  253. authorize!(ticket)
  254. ticket.destroy!
  255. head :ok
  256. end
  257. # GET /api/v1/ticket_customer
  258. # GET /api/v1/tickets_customer
  259. def ticket_customer
  260. # return result
  261. result = Ticket::ScreenOptions.list_by_customer(
  262. current_user: current_user,
  263. customer_id: params[:customer_id],
  264. limit: 15,
  265. )
  266. render json: result
  267. end
  268. # GET /api/v1/ticket_history/1
  269. def ticket_history
  270. # get ticket data
  271. ticket = Ticket.find(params[:id])
  272. authorize!(ticket, :show?)
  273. # get history of ticket
  274. render json: ticket.history_get(true)
  275. end
  276. # GET /api/v1/ticket_related/1
  277. def ticket_related
  278. ticket = Ticket.find(params[:ticket_id])
  279. assets = ticket.assets({})
  280. tickets = TicketPolicy::ReadScope.new(current_user).resolve
  281. .where(
  282. customer_id: ticket.customer_id,
  283. state_id: Ticket::State.by_category(:open).select(:id),
  284. )
  285. .where.not(id: ticket.id)
  286. .reorder(created_at: :desc)
  287. .limit(6)
  288. # if we do not have open related tickets, search for any tickets
  289. tickets ||= TicketPolicy::ReadScope.new(current_user).resolve
  290. .where(customer_id: ticket.customer_id)
  291. .where.not(state_id: Ticket::State.by_category_ids(:merged))
  292. .where.not(id: ticket.id)
  293. .reorder(created_at: :desc)
  294. .limit(6)
  295. # get related assets
  296. ticket_ids_by_customer = []
  297. tickets.each do |ticket_list|
  298. ticket_ids_by_customer.push ticket_list.id
  299. assets = ticket_list.assets(assets)
  300. end
  301. ticket_ids_recent_viewed = []
  302. recent_views = RecentView.list(current_user, 8, 'Ticket')
  303. recent_views.each do |recent_view|
  304. next if recent_view.object.name != 'Ticket'
  305. next if recent_view.o_id == ticket.id
  306. ticket_ids_recent_viewed.push recent_view.o_id
  307. recent_view_ticket = Ticket.find(recent_view.o_id)
  308. assets = recent_view_ticket.assets(assets)
  309. end
  310. # return result
  311. render json: {
  312. assets: assets,
  313. ticket_ids_by_customer: ticket_ids_by_customer,
  314. ticket_ids_recent_viewed: ticket_ids_recent_viewed,
  315. }
  316. end
  317. # GET /api/v1/ticket_recent
  318. def ticket_recent
  319. ticket_ids = RecentView.list(current_user, 10, Ticket.name).map(&:o_id)
  320. tickets = ticket_ids.map { |elem| Ticket.lookup(id: elem) }
  321. assets = ApplicationModel::CanAssets.reduce(tickets)
  322. render json: {
  323. assets: assets,
  324. ticket_ids_recent_viewed: ticket_ids
  325. }
  326. end
  327. # PUT /api/v1/ticket_merge/1/1
  328. def ticket_merge
  329. # check target ticket
  330. target_ticket = Ticket.find_by(number: params[:target_ticket_number])
  331. if !target_ticket
  332. render json: {
  333. result: 'failed',
  334. message: __('The target ticket number could not be found.'),
  335. }
  336. return
  337. end
  338. # check source ticket
  339. source_ticket = Ticket.find_by(id: params[:source_ticket_id])
  340. if !source_ticket
  341. render json: {
  342. result: 'failed',
  343. message: __('The source ticket could not be found.'),
  344. }
  345. return
  346. end
  347. # merge ticket
  348. Service::Ticket::Merge.new(current_user:).execute(source_ticket:, target_ticket:)
  349. # return result
  350. render json: {
  351. result: 'success',
  352. target_ticket: target_ticket.attributes,
  353. source_ticket: source_ticket.attributes,
  354. }
  355. end
  356. # GET /api/v1/ticket_split
  357. def ticket_split
  358. ticket = Ticket.find(params[:ticket_id])
  359. authorize!(ticket, :show?)
  360. assets = ticket.assets({})
  361. article = Ticket::Article.find(params[:article_id])
  362. authorize!(article.ticket, :show?)
  363. assets = article.assets(assets)
  364. render json: {
  365. assets: assets,
  366. attachments: article_attachments_clone(article),
  367. }
  368. end
  369. # GET /api/v1/ticket_create
  370. def ticket_create
  371. # get attributes to update
  372. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  373. view: 'ticket_create',
  374. screen: 'create_middle',
  375. current_user: current_user,
  376. )
  377. render json: attributes_to_change
  378. end
  379. # GET /api/v1/tickets/search
  380. def search
  381. # permit nested conditions
  382. if params[:condition]
  383. params.require(:condition).permit!
  384. end
  385. paginate_with(max: 200, default: 50)
  386. query = params[:query]
  387. if query.respond_to?(:permit!)
  388. query = query.permit!.to_h
  389. end
  390. # build result list
  391. tickets = Ticket.search(
  392. query: query,
  393. condition: params[:condition].to_h,
  394. limit: pagination.limit,
  395. offset: pagination.offset,
  396. order_by: params[:order_by],
  397. sort_by: params[:sort_by],
  398. current_user: current_user,
  399. )
  400. if response_expand?
  401. list = []
  402. tickets.each do |ticket|
  403. list.push ticket.attributes_with_association_names
  404. end
  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 'me@example.com:test' 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 'me@example.com:test' -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import?try=true'
  538. # @example curl -u 'me@example.com:test' -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. # return result
  598. {
  599. ticket_id: ticket.id,
  600. ticket_article_ids: article_ids,
  601. assets: assets,
  602. links: links,
  603. tags: tags,
  604. mentions: mentions.pluck(:id),
  605. time_accountings: time_accountings,
  606. form_meta: attributes_to_change[:form_meta],
  607. }
  608. end
  609. end