tickets_controller.rb 21 KB

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