tickets_controller.rb 19 KB

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