tickets_controller.rb 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. history = ticket.history_get(true)
  249. # return result
  250. render json: history
  251. end
  252. # GET /api/v1/ticket_related/1
  253. def ticket_related
  254. ticket = Ticket.find(params[:ticket_id])
  255. assets = ticket.assets({})
  256. # open tickets by customer
  257. access_condition = Ticket.access_condition(current_user, 'read')
  258. ticket_lists = Ticket
  259. .where(
  260. customer_id: ticket.customer_id,
  261. state_id: Ticket::State.by_category(:open)
  262. )
  263. .where(access_condition)
  264. .where('id != ?', [ ticket.id ])
  265. .order('created_at DESC')
  266. .limit(6)
  267. # if we do not have open related tickets, search for any tickets
  268. if ticket_lists.blank?
  269. ticket_lists = Ticket
  270. .where(
  271. customer_id: ticket.customer_id,
  272. ).where.not(
  273. state_id: Ticket::State.by_category(:merged)
  274. )
  275. .where(access_condition)
  276. .where('id != ?', [ ticket.id ])
  277. .order('created_at DESC')
  278. .limit(6)
  279. end
  280. # get related assets
  281. ticket_ids_by_customer = []
  282. ticket_lists.each do |ticket_list|
  283. ticket_ids_by_customer.push ticket_list.id
  284. assets = ticket_list.assets(assets)
  285. end
  286. ticket_ids_recent_viewed = []
  287. recent_views = RecentView.list(current_user, 8, 'Ticket')
  288. recent_views.each do |recent_view|
  289. next if recent_view.object.name != 'Ticket'
  290. next if recent_view.o_id == ticket.id
  291. ticket_ids_recent_viewed.push recent_view.o_id
  292. recent_view_ticket = Ticket.find(recent_view.o_id)
  293. assets = recent_view_ticket.assets(assets)
  294. end
  295. # return result
  296. render json: {
  297. assets: assets,
  298. ticket_ids_by_customer: ticket_ids_by_customer,
  299. ticket_ids_recent_viewed: ticket_ids_recent_viewed,
  300. }
  301. end
  302. # GET /api/v1/ticket_merge/1/1
  303. def ticket_merge
  304. # check master ticket
  305. ticket_master = Ticket.find_by(number: params[:master_ticket_number])
  306. if !ticket_master
  307. render json: {
  308. result: 'failed',
  309. message: 'No such master ticket number!',
  310. }
  311. return
  312. end
  313. access!(ticket_master, 'change')
  314. # check slave ticket
  315. ticket_slave = Ticket.find_by(id: params[:slave_ticket_id])
  316. if !ticket_slave
  317. render json: {
  318. result: 'failed',
  319. message: 'No such slave ticket!',
  320. }
  321. return
  322. end
  323. access!(ticket_slave, 'change')
  324. # merge ticket
  325. ticket_slave.merge_to(
  326. ticket_id: ticket_master.id,
  327. created_by_id: current_user.id,
  328. )
  329. # return result
  330. render json: {
  331. result: 'success',
  332. master_ticket: ticket_master.attributes,
  333. slave_ticket: ticket_slave.attributes,
  334. }
  335. end
  336. # GET /api/v1/ticket_split
  337. def ticket_split
  338. ticket = Ticket.find(params[:ticket_id])
  339. access!(ticket, 'read')
  340. assets = ticket.assets({})
  341. article = Ticket::Article.find(params[:article_id])
  342. access!(article.ticket, 'read')
  343. assets = article.assets(assets)
  344. render json: {
  345. assets: assets,
  346. attachments: article_attachments_clone(article),
  347. }
  348. end
  349. # GET /api/v1/ticket_create
  350. def ticket_create
  351. # get attributes to update
  352. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  353. current_user: current_user,
  354. )
  355. render json: attributes_to_change
  356. end
  357. # GET /api/v1/tickets/search
  358. def search
  359. # permit nested conditions
  360. if params[:condition]
  361. params.require(:condition).permit!
  362. end
  363. per_page = params[:per_page] || params[:limit] || 50
  364. per_page = per_page.to_i
  365. if per_page > 200
  366. per_page = 200
  367. end
  368. page = params[:page] || 1
  369. page = page.to_i
  370. offset = (page - 1) * per_page
  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: per_page,
  380. offset: 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. permission_check('admin.*')
  409. ticket_count, tickets = Ticket.selectors(params[:condition], 6)
  410. assets = {}
  411. ticket_ids = []
  412. tickets&.each do |ticket|
  413. ticket_ids.push ticket.id
  414. assets = ticket.assets(assets)
  415. end
  416. # return result
  417. render json: {
  418. ticket_ids: ticket_ids,
  419. ticket_count: ticket_count || 0,
  420. assets: assets,
  421. }
  422. end
  423. # GET /api/v1/ticket_stats
  424. def stats
  425. if !params[:user_id] && !params[:organization_id]
  426. raise 'Need user_id or organization_id as param'
  427. end
  428. # lookup open user tickets
  429. limit = 100
  430. assets = {}
  431. access_condition = Ticket.access_condition(current_user, 'read')
  432. user_tickets = {}
  433. if params[:user_id]
  434. user = User.lookup(id: params[:user_id])
  435. if !user
  436. raise "No such user with id #{params[:user_id]}"
  437. end
  438. conditions = {
  439. closed_ids: {
  440. 'ticket.state_id' => {
  441. operator: 'is',
  442. value: Ticket::State.by_category(:closed).pluck(:id),
  443. },
  444. 'ticket.customer_id' => {
  445. operator: 'is',
  446. value: user.id,
  447. },
  448. },
  449. open_ids: {
  450. 'ticket.state_id' => {
  451. operator: 'is',
  452. value: Ticket::State.by_category(:open).pluck(:id),
  453. },
  454. 'ticket.customer_id' => {
  455. operator: 'is',
  456. value: user.id,
  457. },
  458. },
  459. }
  460. conditions.each do |key, local_condition|
  461. user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  462. end
  463. # generate stats by user
  464. condition = {
  465. 'tickets.customer_id' => user.id,
  466. }
  467. user_tickets[:volume_by_year] = ticket_stats_last_year(condition, access_condition)
  468. end
  469. # lookup open org tickets
  470. org_tickets = {}
  471. if params[:organization_id].present?
  472. organization = Organization.lookup(id: params[:organization_id])
  473. if !organization
  474. raise "No such organization with id #{params[:organization_id]}"
  475. end
  476. conditions = {
  477. closed_ids: {
  478. 'ticket.state_id' => {
  479. operator: 'is',
  480. value: Ticket::State.by_category(:closed).pluck(:id),
  481. },
  482. 'ticket.organization_id' => {
  483. operator: 'is',
  484. value: organization.id,
  485. },
  486. },
  487. open_ids: {
  488. 'ticket.state_id' => {
  489. operator: 'is',
  490. value: Ticket::State.by_category(:open).pluck(:id),
  491. },
  492. 'ticket.organization_id' => {
  493. operator: 'is',
  494. value: organization.id,
  495. },
  496. },
  497. }
  498. conditions.each do |key, local_condition|
  499. org_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  500. end
  501. # generate stats by org
  502. condition = {
  503. 'tickets.organization_id' => organization.id,
  504. }
  505. org_tickets[:volume_by_year] = ticket_stats_last_year(condition, access_condition)
  506. end
  507. # return result
  508. render json: {
  509. user: user_tickets,
  510. organization: org_tickets,
  511. assets: assets,
  512. }
  513. end
  514. # @path [GET] /tickets/import_example
  515. #
  516. # @summary Download of example CSV file.
  517. # @notes The requester have 'admin' permissions to be able to download it.
  518. # @example curl -u 'me@example.com:test' http://localhost:3000/api/v1/tickets/import_example
  519. #
  520. # @response_message 200 File download.
  521. # @response_message 401 Invalid session.
  522. def import_example
  523. permission_check('admin')
  524. csv_string = Ticket.csv_example(
  525. col_sep: ',',
  526. )
  527. send_data(
  528. csv_string,
  529. filename: 'example.csv',
  530. type: 'text/csv',
  531. disposition: 'attachment'
  532. )
  533. end
  534. # @path [POST] /tickets/import
  535. #
  536. # @summary Starts import.
  537. # @notes The requester have 'admin' permissions to be create a new import.
  538. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import?try=true'
  539. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import'
  540. #
  541. # @response_message 201 Import started.
  542. # @response_message 401 Invalid session.
  543. def import_start
  544. permission_check('admin')
  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 follow_up_possible_check
  564. ticket = Ticket.find(params[:id])
  565. return true if ticket.group.follow_up_possible != 'new_ticket' # check if the setting for follow_up_possible is disabled
  566. return true if ticket.state.name != 'closed' # check if the ticket state is already closed
  567. raise Exceptions::UnprocessableEntity, 'Cannot follow up on a closed ticket. Please create a new ticket.'
  568. end
  569. def ticket_all(ticket)
  570. # get attributes to update
  571. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  572. current_user: current_user,
  573. ticket: ticket
  574. )
  575. # get related users
  576. assets = attributes_to_change[:assets]
  577. assets = ticket.assets(assets)
  578. # get related users
  579. article_ids = []
  580. ticket.articles.each do |article|
  581. # ignore internal article if customer is requesting
  582. next if article.internal == true && current_user.permissions?('ticket.customer')
  583. article_ids.push article.id
  584. assets = article.assets(assets)
  585. end
  586. # get links
  587. links = Link.list(
  588. link_object: 'Ticket',
  589. link_object_value: ticket.id,
  590. )
  591. link_list = []
  592. links.each do |item|
  593. link_list.push item
  594. if item['link_object'] == 'Ticket'
  595. linked_ticket = Ticket.lookup(id: item['link_object_value'])
  596. assets = linked_ticket.assets(assets)
  597. end
  598. end
  599. # get tags
  600. tags = ticket.tag_list
  601. # return result
  602. {
  603. ticket_id: ticket.id,
  604. ticket_article_ids: article_ids,
  605. assets: assets,
  606. links: link_list,
  607. tags: tags,
  608. form_meta: attributes_to_change[:form_meta],
  609. }
  610. end
  611. end