tickets_controller.rb 21 KB

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