tickets_controller.rb 21 KB

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