tickets_controller.rb 20 KB

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