tickets_controller.rb 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. # only apply preferences changes (keep not updated keys/values)
  195. clean_params = ticket.param_preferences_merge(clean_params)
  196. # overwrite params
  197. if !current_user.permissions?('ticket.agent')
  198. %i[owner owner_id customer customer_id organization organization_id preferences].each do |key|
  199. clean_params.delete(key)
  200. end
  201. end
  202. ticket.with_lock do
  203. ticket.update!(clean_params)
  204. if params[:article]
  205. article_create(ticket, params[:article])
  206. end
  207. end
  208. if response_expand?
  209. result = ticket.reload.attributes_with_association_names
  210. render json: result, status: :ok
  211. return
  212. end
  213. if response_full?
  214. full = Ticket.full(params[:id])
  215. render json: full, status: :ok
  216. return
  217. end
  218. if response_all?
  219. render json: ticket_all(ticket.reload), status: :ok
  220. return
  221. end
  222. render json: ticket.reload.attributes_with_association_ids, status: :ok
  223. end
  224. # DELETE /api/v1/tickets/1
  225. def destroy
  226. ticket = Ticket.find(params[:id])
  227. access!(ticket, 'delete')
  228. raise Exceptions::NotAuthorized, 'Not authorized (admin permission required)!' if !current_user.permissions?('admin')
  229. ticket.destroy!
  230. head :ok
  231. end
  232. # GET /api/v1/ticket_customer
  233. # GET /api/v1/tickets_customer
  234. def ticket_customer
  235. # return result
  236. result = Ticket::ScreenOptions.list_by_customer(
  237. customer_id: params[:customer_id],
  238. limit: 15,
  239. )
  240. render json: result
  241. end
  242. # GET /api/v1/ticket_history/1
  243. def ticket_history
  244. # get ticket data
  245. ticket = Ticket.find(params[:id])
  246. access!(ticket, 'read')
  247. # get history of ticket
  248. render json: ticket.history_get(true)
  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. per_page = params[:per_page] || params[:limit] || 50
  362. per_page = per_page.to_i
  363. if per_page > 200
  364. per_page = 200
  365. end
  366. page = params[:page] || 1
  367. page = page.to_i
  368. offset = (page - 1) * per_page
  369. query = params[:query]
  370. if query.respond_to?(:permit!)
  371. query = query.permit!.to_h
  372. end
  373. # build result list
  374. tickets = Ticket.search(
  375. query: query,
  376. condition: params[:condition].to_h,
  377. limit: per_page,
  378. offset: offset,
  379. order_by: params[:order_by],
  380. sort_by: params[:sort_by],
  381. current_user: current_user,
  382. )
  383. if response_expand?
  384. list = []
  385. tickets.each do |ticket|
  386. list.push ticket.attributes_with_association_names
  387. end
  388. render json: list, status: :ok
  389. return
  390. end
  391. assets = {}
  392. ticket_result = []
  393. tickets.each do |ticket|
  394. ticket_result.push ticket.id
  395. assets = ticket.assets(assets)
  396. end
  397. # return result
  398. render json: {
  399. tickets: ticket_result,
  400. tickets_count: tickets.count,
  401. assets: assets,
  402. }
  403. end
  404. # GET /api/v1/tickets/selector
  405. def selector
  406. permission_check('admin.*')
  407. ticket_count, tickets = Ticket.selectors(params[:condition], 6)
  408. assets = {}
  409. ticket_ids = []
  410. tickets&.each do |ticket|
  411. ticket_ids.push ticket.id
  412. assets = ticket.assets(assets)
  413. end
  414. # return result
  415. render json: {
  416. ticket_ids: ticket_ids,
  417. ticket_count: ticket_count || 0,
  418. assets: assets,
  419. }
  420. end
  421. # GET /api/v1/ticket_stats
  422. def stats
  423. if !params[:user_id] && !params[:organization_id]
  424. raise 'Need user_id or organization_id as param'
  425. end
  426. # lookup open user tickets
  427. limit = 100
  428. assets = {}
  429. access_condition = Ticket.access_condition(current_user, 'read')
  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, access_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, access_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 401 Invalid session.
  520. def import_example
  521. permission_check('admin')
  522. csv_string = Ticket.csv_example(
  523. col_sep: ',',
  524. )
  525. send_data(
  526. csv_string,
  527. filename: 'example.csv',
  528. type: 'text/csv',
  529. disposition: 'attachment'
  530. )
  531. end
  532. # @path [POST] /tickets/import
  533. #
  534. # @summary Starts import.
  535. # @notes The requester have 'admin' permissions to be create a new import.
  536. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import?try=true'
  537. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import'
  538. #
  539. # @response_message 201 Import started.
  540. # @response_message 401 Invalid session.
  541. def import_start
  542. permission_check('admin')
  543. if Setting.get('import_mode') != true
  544. raise 'Only can import tickets if system is in import mode.'
  545. end
  546. string = params[:data]
  547. if string.blank? && params[:file].present?
  548. string = params[:file].read.force_encoding('utf-8')
  549. end
  550. raise Exceptions::UnprocessableEntity, 'No source data submitted!' if string.blank?
  551. result = Ticket.csv_import(
  552. string: string,
  553. parse_params: {
  554. col_sep: params[:col_sep] || ',',
  555. },
  556. try: params[:try],
  557. )
  558. render json: result, status: :ok
  559. end
  560. private
  561. def follow_up_possible_check
  562. ticket = Ticket.find(params[:id])
  563. return true if ticket.group.follow_up_possible != 'new_ticket' # check if the setting for follow_up_possible is disabled
  564. return true if ticket.state.name != 'closed' # check if the ticket state is already closed
  565. raise Exceptions::UnprocessableEntity, 'Cannot follow up on a closed ticket. Please create a new ticket.'
  566. end
  567. def ticket_all(ticket)
  568. # get attributes to update
  569. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  570. current_user: current_user,
  571. ticket: ticket
  572. )
  573. # get related users
  574. assets = attributes_to_change[:assets]
  575. assets = ticket.assets(assets)
  576. # get related users
  577. article_ids = []
  578. ticket.articles.each do |article|
  579. # ignore internal article if customer is requesting
  580. next if article.internal == true && current_user.permissions?('ticket.customer')
  581. article_ids.push article.id
  582. assets = article.assets(assets)
  583. end
  584. # get links
  585. links = Link.list(
  586. link_object: 'Ticket',
  587. link_object_value: ticket.id,
  588. )
  589. link_list = []
  590. links.each do |item|
  591. link_list.push item
  592. if item['link_object'] == 'Ticket'
  593. linked_ticket = Ticket.lookup(id: item['link_object_value'])
  594. assets = linked_ticket.assets(assets)
  595. end
  596. end
  597. # get tags
  598. tags = ticket.tag_list
  599. # return result
  600. {
  601. ticket_id: ticket.id,
  602. ticket_article_ids: article_ids,
  603. assets: assets,
  604. links: link_list,
  605. tags: tags,
  606. form_meta: attributes_to_change[:form_meta],
  607. }
  608. end
  609. end