tickets_controller.rb 20 KB

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