tickets_controller.rb 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class TicketsController < ApplicationController
  3. include CreatesTicketArticles
  4. include ClonesTicketArticleAttachments
  5. include ChecksUserAttributesByCurrentUserPermission
  6. include TicketStats
  7. prepend_before_action -> { authorize! }, only: %i[create selector import_example import_start ticket_customer ticket_history ticket_related ticket_recent ticket_merge ticket_split]
  8. prepend_before_action :authentication_check
  9. # GET /api/v1/tickets
  10. def index
  11. offset = 0
  12. per_page = 100
  13. if params[:page] && params[:per_page]
  14. offset = (params[:page].to_i - 1) * params[:per_page].to_i
  15. per_page = params[:per_page].to_i
  16. end
  17. if per_page > 100
  18. per_page = 100
  19. end
  20. access_condition = Ticket.access_condition(current_user, 'read')
  21. tickets = Ticket.where(access_condition).order(id: :asc).offset(offset).limit(per_page)
  22. if response_expand?
  23. list = []
  24. tickets.each do |ticket|
  25. list.push ticket.attributes_with_association_names
  26. end
  27. render json: list, status: :ok
  28. return
  29. end
  30. if response_full?
  31. assets = {}
  32. item_ids = []
  33. tickets.each do |item|
  34. item_ids.push item.id
  35. assets = item.assets(assets)
  36. end
  37. render json: {
  38. record_ids: item_ids,
  39. assets: assets,
  40. }, status: :ok
  41. return
  42. end
  43. render json: tickets
  44. end
  45. # GET /api/v1/tickets/1
  46. def show
  47. ticket = Ticket.find(params[:id])
  48. authorize!(ticket)
  49. if response_expand?
  50. result = ticket.attributes_with_association_names
  51. render json: result, status: :ok
  52. return
  53. end
  54. if response_full?
  55. full = Ticket.full(params[:id])
  56. render json: full
  57. return
  58. end
  59. if response_all?
  60. render json: ticket_all(ticket)
  61. return
  62. end
  63. render json: ticket
  64. end
  65. # POST /api/v1/tickets
  66. def create
  67. customer = {}
  68. if params[:customer].instance_of?(ActionController::Parameters)
  69. customer = params[:customer]
  70. params.delete(:customer)
  71. end
  72. clean_params = Ticket.association_name_to_id_convert(params)
  73. # overwrite params
  74. if !current_user.permissions?('ticket.agent')
  75. %i[owner owner_id customer customer_id organization organization_id preferences].each do |key|
  76. clean_params.delete(key)
  77. end
  78. clean_params[:customer_id] = current_user.id
  79. end
  80. # try to create customer if needed
  81. if clean_params[:customer_id].present? && clean_params[:customer_id] =~ %r{^guess:(.+?)$}
  82. email_address = $1
  83. email_address_validation = EmailAddressValidation.new(email_address)
  84. if !email_address_validation.valid_format?
  85. render json: { error: "Invalid email '#{email_address}' of customer" }, status: :unprocessable_entity
  86. return
  87. end
  88. local_customer = User.find_by(email: email_address.downcase)
  89. if !local_customer
  90. role_ids = Role.signup_role_ids
  91. local_customer = User.create(
  92. firstname: '',
  93. lastname: '',
  94. email: email_address,
  95. password: '',
  96. active: true,
  97. role_ids: role_ids,
  98. )
  99. end
  100. clean_params[:customer_id] = local_customer.id
  101. end
  102. # try to create customer if needed
  103. if clean_params[:customer_id].blank? && customer.present?
  104. check_attributes_by_current_user_permission(customer)
  105. clean_customer = User.association_name_to_id_convert(customer)
  106. local_customer = nil
  107. if !local_customer && clean_customer[:id].present?
  108. local_customer = User.find_by(id: clean_customer[:id])
  109. end
  110. if !local_customer && clean_customer[:email].present?
  111. local_customer = User.find_by(email: clean_customer[:email].downcase)
  112. end
  113. if !local_customer && clean_customer[:login].present?
  114. local_customer = User.find_by(login: clean_customer[:login].downcase)
  115. end
  116. if !local_customer
  117. role_ids = Role.signup_role_ids
  118. local_customer = User.new(clean_customer)
  119. local_customer.role_ids = role_ids
  120. local_customer.save!
  121. end
  122. clean_params[:customer_id] = local_customer.id
  123. end
  124. clean_params = Ticket.param_cleanup(clean_params, true)
  125. ticket = Ticket.new(clean_params)
  126. authorize!(ticket, :create?)
  127. # check if article is given
  128. if !params[:article]
  129. render json: { error: 'article hash is missing' }, status: :unprocessable_entity
  130. return
  131. end
  132. # create ticket
  133. ticket.save!
  134. ticket.with_lock do
  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. end
  154. # create links (e. g. in case of ticket split)
  155. # links: {
  156. # Ticket: {
  157. # parent: [ticket_id1, ticket_id2, ...]
  158. # normal: [ticket_id1, ticket_id2, ...]
  159. # child: [ticket_id1, ticket_id2, ...]
  160. # },
  161. # }
  162. if params[:links].present?
  163. link = params[:links].permit!.to_h
  164. raise Exceptions::UnprocessableEntity, 'Invalid link structure' if !link.is_a? Hash
  165. link.each do |target_object, link_types_with_object_ids|
  166. raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object)' if !link_types_with_object_ids.is_a? Hash
  167. link_types_with_object_ids.each do |link_type, object_ids|
  168. raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object->LinkType)' if !object_ids.is_a? Array
  169. object_ids.each do |local_object_id|
  170. link = Link.add(
  171. link_type: link_type,
  172. link_object_target: target_object,
  173. link_object_target_value: local_object_id,
  174. link_object_source: 'Ticket',
  175. link_object_source_value: ticket.id,
  176. )
  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. # disable changes on ticket number
  207. clean_params.delete('number')
  208. # overwrite params
  209. if !current_user.permissions?('ticket.agent')
  210. %i[owner owner_id customer customer_id organization organization_id preferences].each do |key|
  211. clean_params.delete(key)
  212. end
  213. end
  214. ticket.with_lock do
  215. ticket.update!(clean_params)
  216. if params[:article].present?
  217. article_create(ticket, params[:article])
  218. end
  219. end
  220. if response_expand?
  221. result = ticket.reload.attributes_with_association_names
  222. render json: result, status: :ok
  223. return
  224. end
  225. if response_full?
  226. full = Ticket.full(params[:id])
  227. render json: full, status: :ok
  228. return
  229. end
  230. if response_all?
  231. render json: ticket_all(ticket.reload), status: :ok
  232. return
  233. end
  234. render json: ticket.reload.attributes_with_association_ids, status: :ok
  235. end
  236. # DELETE /api/v1/tickets/1
  237. def destroy
  238. ticket = Ticket.find(params[:id])
  239. authorize!(ticket)
  240. ticket.destroy!
  241. head :ok
  242. end
  243. # GET /api/v1/ticket_customer
  244. # GET /api/v1/tickets_customer
  245. def ticket_customer
  246. # return result
  247. result = Ticket::ScreenOptions.list_by_customer(
  248. current_user: current_user,
  249. customer_id: params[:customer_id],
  250. limit: 15,
  251. )
  252. render json: result
  253. end
  254. # GET /api/v1/ticket_history/1
  255. def ticket_history
  256. # get ticket data
  257. ticket = Ticket.find(params[:id])
  258. authorize!(ticket, :show?)
  259. # get history of ticket
  260. render json: ticket.history_get(true)
  261. end
  262. # GET /api/v1/ticket_related/1
  263. def ticket_related
  264. ticket = Ticket.find(params[:ticket_id])
  265. assets = ticket.assets({})
  266. # open tickets by customer
  267. access_condition = Ticket.access_condition(current_user, 'read')
  268. ticket_lists = Ticket
  269. .where(
  270. customer_id: ticket.customer_id,
  271. state_id: Ticket::State.by_category(:open).pluck(:id), # rubocop:disable Rails/PluckInWhere
  272. )
  273. .where(access_condition)
  274. .where.not(id: [ ticket.id ])
  275. .order(created_at: :desc)
  276. .limit(6)
  277. # if we do not have open related tickets, search for any tickets
  278. if ticket_lists.blank?
  279. ticket_lists = Ticket
  280. .where(
  281. customer_id: ticket.customer_id,
  282. ).where.not(
  283. state_id: Ticket::State.by_category(:merged).pluck(:id),
  284. )
  285. .where(access_condition)
  286. .where.not(id: [ ticket.id ])
  287. .order(created_at: :desc)
  288. .limit(6)
  289. end
  290. # get related assets
  291. ticket_ids_by_customer = []
  292. ticket_lists.each do |ticket_list|
  293. ticket_ids_by_customer.push ticket_list.id
  294. assets = ticket_list.assets(assets)
  295. end
  296. ticket_ids_recent_viewed = []
  297. recent_views = RecentView.list(current_user, 8, 'Ticket')
  298. recent_views.each do |recent_view|
  299. next if recent_view.object.name != 'Ticket'
  300. next if recent_view.o_id == ticket.id
  301. ticket_ids_recent_viewed.push recent_view.o_id
  302. recent_view_ticket = Ticket.find(recent_view.o_id)
  303. assets = recent_view_ticket.assets(assets)
  304. end
  305. # return result
  306. render json: {
  307. assets: assets,
  308. ticket_ids_by_customer: ticket_ids_by_customer,
  309. ticket_ids_recent_viewed: ticket_ids_recent_viewed,
  310. }
  311. end
  312. # GET /api/v1/ticket_recent
  313. def ticket_recent
  314. ticket_ids = RecentView.list(current_user, 10, Ticket.name).map(&:o_id)
  315. tickets = ticket_ids.map { |elem| Ticket.lookup(id: elem) }
  316. assets = ApplicationModel::CanAssets.reduce(tickets)
  317. render json: {
  318. assets: assets,
  319. ticket_ids_recent_viewed: ticket_ids
  320. }
  321. end
  322. # PUT /api/v1/ticket_merge/1/1
  323. def ticket_merge
  324. # check master ticket
  325. ticket_master = Ticket.find_by(number: params[:master_ticket_number])
  326. if !ticket_master
  327. render json: {
  328. result: 'failed',
  329. message: 'No such master ticket number!',
  330. }
  331. return
  332. end
  333. authorize!(ticket_master, :update?)
  334. # check slave ticket
  335. ticket_slave = Ticket.find_by(id: params[:slave_ticket_id])
  336. if !ticket_slave
  337. render json: {
  338. result: 'failed',
  339. message: 'No such slave ticket!',
  340. }
  341. return
  342. end
  343. authorize!(ticket_slave, :update?)
  344. # merge ticket
  345. ticket_slave.merge_to(
  346. ticket_id: ticket_master.id,
  347. created_by_id: current_user.id,
  348. )
  349. # return result
  350. render json: {
  351. result: 'success',
  352. master_ticket: ticket_master.attributes,
  353. slave_ticket: ticket_slave.attributes,
  354. }
  355. end
  356. # GET /api/v1/ticket_split
  357. def ticket_split
  358. ticket = Ticket.find(params[:ticket_id])
  359. authorize!(ticket, :show?)
  360. assets = ticket.assets({})
  361. article = Ticket::Article.find(params[:article_id])
  362. authorize!(article.ticket, :show?)
  363. assets = article.assets(assets)
  364. render json: {
  365. assets: assets,
  366. attachments: article_attachments_clone(article),
  367. }
  368. end
  369. # GET /api/v1/ticket_create
  370. def ticket_create
  371. # get attributes to update
  372. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  373. view: 'ticket_create',
  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. per_page = params[:per_page] || params[:limit] || 50
  385. per_page = per_page.to_i
  386. if per_page > 200
  387. per_page = 200
  388. end
  389. page = params[:page] || 1
  390. page = page.to_i
  391. offset = (page - 1) * per_page
  392. query = params[:query]
  393. if query.respond_to?(:permit!)
  394. query = query.permit!.to_h
  395. end
  396. # build result list
  397. tickets = Ticket.search(
  398. query: query,
  399. condition: params[:condition].to_h,
  400. limit: per_page,
  401. offset: offset,
  402. order_by: params[:order_by],
  403. sort_by: params[:sort_by],
  404. current_user: current_user,
  405. )
  406. if response_expand?
  407. list = []
  408. tickets.each do |ticket|
  409. list.push ticket.attributes_with_association_names
  410. end
  411. render json: list, status: :ok
  412. return
  413. end
  414. assets = {}
  415. ticket_result = []
  416. tickets.each do |ticket|
  417. ticket_result.push ticket.id
  418. assets = ticket.assets(assets)
  419. end
  420. # return result
  421. render json: {
  422. tickets: ticket_result,
  423. tickets_count: tickets.count,
  424. assets: assets,
  425. }
  426. end
  427. # GET /api/v1/tickets/selector
  428. def selector
  429. ticket_count, tickets = Ticket.selectors(params[:condition], limit: 6, execution_time: true)
  430. assets = {}
  431. ticket_ids = []
  432. tickets&.each do |ticket|
  433. ticket_ids.push ticket.id
  434. assets = ticket.assets(assets)
  435. end
  436. # return result
  437. render json: {
  438. ticket_ids: ticket_ids,
  439. ticket_count: ticket_count || 0,
  440. assets: assets,
  441. }
  442. end
  443. # GET /api/v1/ticket_stats
  444. def stats
  445. if !params[:user_id] && !params[:organization_id]
  446. raise 'Need user_id or organization_id as param'
  447. end
  448. # lookup open user tickets
  449. limit = 100
  450. assets = {}
  451. access_condition = Ticket.access_condition(current_user, 'read')
  452. user_tickets = {}
  453. if params[:user_id]
  454. user = User.lookup(id: params[:user_id])
  455. if !user
  456. raise "No such user with id #{params[:user_id]}"
  457. end
  458. conditions = {
  459. closed_ids: {
  460. 'ticket.state_id' => {
  461. operator: 'is',
  462. value: Ticket::State.by_category(:closed).pluck(:id),
  463. },
  464. 'ticket.customer_id' => {
  465. operator: 'is',
  466. value: user.id,
  467. },
  468. },
  469. open_ids: {
  470. 'ticket.state_id' => {
  471. operator: 'is',
  472. value: Ticket::State.by_category(:open).pluck(:id),
  473. },
  474. 'ticket.customer_id' => {
  475. operator: 'is',
  476. value: user.id,
  477. },
  478. },
  479. }
  480. conditions.each do |key, local_condition|
  481. user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  482. end
  483. # generate stats by user
  484. condition = {
  485. 'tickets.customer_id' => user.id,
  486. }
  487. user_tickets[:volume_by_year] = ticket_stats_last_year(condition, access_condition)
  488. end
  489. # lookup open org tickets
  490. org_tickets = {}
  491. if params[:organization_id].present?
  492. organization = Organization.lookup(id: params[:organization_id])
  493. if !organization
  494. raise "No such organization with id #{params[:organization_id]}"
  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.id,
  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.id,
  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.id,
  524. }
  525. org_tickets[:volume_by_year] = ticket_stats_last_year(condition, access_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 'Only can import tickets 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. )
  587. # get related users
  588. assets = attributes_to_change[:assets]
  589. assets = ticket.assets(assets)
  590. # get related users
  591. article_ids = []
  592. ticket.articles.each do |article|
  593. next if !authorized?(article, :show?)
  594. article_ids.push article.id
  595. assets = article.assets(assets)
  596. end
  597. # get links
  598. links = Link.list(
  599. link_object: 'Ticket',
  600. link_object_value: ticket.id,
  601. )
  602. assets = Link.reduce_assets(assets, links)
  603. # get tags
  604. tags = ticket.tag_list
  605. # get mentions
  606. mentions = Mention.where(mentionable: ticket).order(created_at: :desc)
  607. mentions.each do |mention|
  608. assets = mention.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