tickets_controller.rb 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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_address = $1
  83. email_address_validation = EmailAddressValidation.new(email_address)
  84. if !email_address_validation.valid_format?
  85. render json: { error: 'Invalid email 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. # check if article is given
  127. if !params[:article]
  128. render json: { error: 'article hash is missing' }, status: :unprocessable_entity
  129. return
  130. end
  131. # create ticket
  132. ticket.save!
  133. ticket.with_lock do
  134. # create tags if given
  135. if params[:tags].present?
  136. tags = params[:tags].split(/,/)
  137. tags.each do |tag|
  138. ticket.tag_add(tag)
  139. end
  140. end
  141. # create article if given
  142. if params[:article]
  143. article_create(ticket, params[:article])
  144. end
  145. end
  146. # create links (e. g. in case of ticket split)
  147. # links: {
  148. # Ticket: {
  149. # parent: [ticket_id1, ticket_id2, ...]
  150. # normal: [ticket_id1, ticket_id2, ...]
  151. # child: [ticket_id1, ticket_id2, ...]
  152. # },
  153. # }
  154. if params[:links].present?
  155. link = params[:links].permit!.to_h
  156. raise Exceptions::UnprocessableEntity, 'Invalid link structure' if !link.is_a? Hash
  157. link.each do |target_object, link_types_with_object_ids|
  158. raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object)' if !link_types_with_object_ids.is_a? Hash
  159. link_types_with_object_ids.each do |link_type, object_ids|
  160. raise Exceptions::UnprocessableEntity, 'Invalid link structure (Object->LinkType)' if !object_ids.is_a? Array
  161. object_ids.each do |local_object_id|
  162. link = Link.add(
  163. link_type: link_type,
  164. link_object_target: target_object,
  165. link_object_target_value: local_object_id,
  166. link_object_source: 'Ticket',
  167. link_object_source_value: ticket.id,
  168. )
  169. end
  170. end
  171. end
  172. end
  173. if response_expand?
  174. result = ticket.reload.attributes_with_association_names
  175. render json: result, status: :created
  176. return
  177. end
  178. if response_full?
  179. full = Ticket.full(ticket.id)
  180. render json: full, status: :created
  181. return
  182. end
  183. if response_all?
  184. render json: ticket_all(ticket.reload), status: :created
  185. return
  186. end
  187. render json: ticket.reload.attributes_with_association_ids, status: :created
  188. end
  189. # PUT /api/v1/tickets/1
  190. def update
  191. ticket = Ticket.find(params[:id])
  192. access!(ticket, 'change')
  193. clean_params = Ticket.association_name_to_id_convert(params)
  194. clean_params = Ticket.param_cleanup(clean_params, true)
  195. # only apply preferences changes (keep not updated keys/values)
  196. clean_params = ticket.param_preferences_merge(clean_params)
  197. # overwrite params
  198. if !current_user.permissions?('ticket.agent')
  199. %i[owner owner_id customer customer_id organization organization_id preferences].each do |key|
  200. clean_params.delete(key)
  201. end
  202. end
  203. ticket.with_lock do
  204. ticket.update!(clean_params)
  205. if params[:article]
  206. article_create(ticket, params[:article])
  207. end
  208. end
  209. if response_expand?
  210. result = ticket.reload.attributes_with_association_names
  211. render json: result, status: :ok
  212. return
  213. end
  214. if response_full?
  215. full = Ticket.full(params[:id])
  216. render json: full, status: :ok
  217. return
  218. end
  219. if response_all?
  220. render json: ticket_all(ticket.reload), status: :ok
  221. return
  222. end
  223. render json: ticket.reload.attributes_with_association_ids, status: :ok
  224. end
  225. # DELETE /api/v1/tickets/1
  226. def destroy
  227. ticket = Ticket.find(params[:id])
  228. access!(ticket, 'delete')
  229. raise Exceptions::NotAuthorized, 'Not authorized (admin permission required)!' if !current_user.permissions?('admin')
  230. ticket.destroy!
  231. head :ok
  232. end
  233. # GET /api/v1/ticket_customer
  234. # GET /api/v1/tickets_customer
  235. def ticket_customer
  236. # return result
  237. result = Ticket::ScreenOptions.list_by_customer(
  238. current_user: current_user,
  239. customer_id: params[:customer_id],
  240. limit: 15,
  241. )
  242. render json: result
  243. end
  244. # GET /api/v1/ticket_history/1
  245. def ticket_history
  246. # get ticket data
  247. ticket = Ticket.find(params[:id])
  248. access!(ticket, 'read')
  249. # get history of ticket
  250. render json: ticket.history_get(true)
  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).pluck(:id),
  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).pluck(:id),
  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_recent
  303. def ticket_recent
  304. ticket_ids = RecentView.list(current_user, 10, Ticket.name).map(&:o_id)
  305. tickets = ticket_ids.map { |elem| Ticket.lookup(id: elem) }
  306. assets = ApplicationModel::CanAssets.reduce(tickets)
  307. render json: {
  308. assets: assets,
  309. ticket_ids_recent_viewed: ticket_ids
  310. }
  311. end
  312. # GET /api/v1/ticket_merge/1/1
  313. def ticket_merge
  314. # check master ticket
  315. ticket_master = Ticket.find_by(number: params[:master_ticket_number])
  316. if !ticket_master
  317. render json: {
  318. result: 'failed',
  319. message: 'No such master ticket number!',
  320. }
  321. return
  322. end
  323. access!(ticket_master, 'change')
  324. # check slave ticket
  325. ticket_slave = Ticket.find_by(id: params[:slave_ticket_id])
  326. if !ticket_slave
  327. render json: {
  328. result: 'failed',
  329. message: 'No such slave ticket!',
  330. }
  331. return
  332. end
  333. access!(ticket_slave, 'change')
  334. # merge ticket
  335. ticket_slave.merge_to(
  336. ticket_id: ticket_master.id,
  337. created_by_id: current_user.id,
  338. )
  339. # return result
  340. render json: {
  341. result: 'success',
  342. master_ticket: ticket_master.attributes,
  343. slave_ticket: ticket_slave.attributes,
  344. }
  345. end
  346. # GET /api/v1/ticket_split
  347. def ticket_split
  348. ticket = Ticket.find(params[:ticket_id])
  349. access!(ticket, 'read')
  350. assets = ticket.assets({})
  351. article = Ticket::Article.find(params[:article_id])
  352. access!(article.ticket, 'read')
  353. assets = article.assets(assets)
  354. render json: {
  355. assets: assets,
  356. attachments: article_attachments_clone(article),
  357. }
  358. end
  359. # GET /api/v1/ticket_create
  360. def ticket_create
  361. # get attributes to update
  362. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  363. current_user: current_user,
  364. )
  365. render json: attributes_to_change
  366. end
  367. # GET /api/v1/tickets/search
  368. def search
  369. # permit nested conditions
  370. if params[:condition]
  371. params.require(:condition).permit!
  372. end
  373. per_page = params[:per_page] || params[:limit] || 50
  374. per_page = per_page.to_i
  375. if per_page > 200
  376. per_page = 200
  377. end
  378. page = params[:page] || 1
  379. page = page.to_i
  380. offset = (page - 1) * per_page
  381. query = params[:query]
  382. if query.respond_to?(:permit!)
  383. query = query.permit!.to_h
  384. end
  385. # build result list
  386. tickets = Ticket.search(
  387. query: query,
  388. condition: params[:condition].to_h,
  389. limit: per_page,
  390. offset: offset,
  391. order_by: params[:order_by],
  392. sort_by: params[:sort_by],
  393. current_user: current_user,
  394. )
  395. if response_expand?
  396. list = []
  397. tickets.each do |ticket|
  398. list.push ticket.attributes_with_association_names
  399. end
  400. render json: list, status: :ok
  401. return
  402. end
  403. assets = {}
  404. ticket_result = []
  405. tickets.each do |ticket|
  406. ticket_result.push ticket.id
  407. assets = ticket.assets(assets)
  408. end
  409. # return result
  410. render json: {
  411. tickets: ticket_result,
  412. tickets_count: tickets.count,
  413. assets: assets,
  414. }
  415. end
  416. # GET /api/v1/tickets/selector
  417. def selector
  418. permission_check('admin.*')
  419. ticket_count, tickets = Ticket.selectors(params[:condition], limit: 6)
  420. assets = {}
  421. ticket_ids = []
  422. tickets&.each do |ticket|
  423. ticket_ids.push ticket.id
  424. assets = ticket.assets(assets)
  425. end
  426. # return result
  427. render json: {
  428. ticket_ids: ticket_ids,
  429. ticket_count: ticket_count || 0,
  430. assets: assets,
  431. }
  432. end
  433. # GET /api/v1/ticket_stats
  434. def stats
  435. if !params[:user_id] && !params[:organization_id]
  436. raise 'Need user_id or organization_id as param'
  437. end
  438. # lookup open user tickets
  439. limit = 100
  440. assets = {}
  441. access_condition = Ticket.access_condition(current_user, 'read')
  442. user_tickets = {}
  443. if params[:user_id]
  444. user = User.lookup(id: params[:user_id])
  445. if !user
  446. raise "No such user with id #{params[:user_id]}"
  447. end
  448. conditions = {
  449. closed_ids: {
  450. 'ticket.state_id' => {
  451. operator: 'is',
  452. value: Ticket::State.by_category(:closed).pluck(:id),
  453. },
  454. 'ticket.customer_id' => {
  455. operator: 'is',
  456. value: user.id,
  457. },
  458. },
  459. open_ids: {
  460. 'ticket.state_id' => {
  461. operator: 'is',
  462. value: Ticket::State.by_category(:open).pluck(:id),
  463. },
  464. 'ticket.customer_id' => {
  465. operator: 'is',
  466. value: user.id,
  467. },
  468. },
  469. }
  470. conditions.each do |key, local_condition|
  471. user_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  472. end
  473. # generate stats by user
  474. condition = {
  475. 'tickets.customer_id' => user.id,
  476. }
  477. user_tickets[:volume_by_year] = ticket_stats_last_year(condition, access_condition)
  478. end
  479. # lookup open org tickets
  480. org_tickets = {}
  481. if params[:organization_id].present?
  482. organization = Organization.lookup(id: params[:organization_id])
  483. if !organization
  484. raise "No such organization with id #{params[:organization_id]}"
  485. end
  486. conditions = {
  487. closed_ids: {
  488. 'ticket.state_id' => {
  489. operator: 'is',
  490. value: Ticket::State.by_category(:closed).pluck(:id),
  491. },
  492. 'ticket.organization_id' => {
  493. operator: 'is',
  494. value: organization.id,
  495. },
  496. },
  497. open_ids: {
  498. 'ticket.state_id' => {
  499. operator: 'is',
  500. value: Ticket::State.by_category(:open).pluck(:id),
  501. },
  502. 'ticket.organization_id' => {
  503. operator: 'is',
  504. value: organization.id,
  505. },
  506. },
  507. }
  508. conditions.each do |key, local_condition|
  509. org_tickets[key] = ticket_ids_and_assets(local_condition, current_user, limit, assets)
  510. end
  511. # generate stats by org
  512. condition = {
  513. 'tickets.organization_id' => organization.id,
  514. }
  515. org_tickets[:volume_by_year] = ticket_stats_last_year(condition, access_condition)
  516. end
  517. # return result
  518. render json: {
  519. user: user_tickets,
  520. organization: org_tickets,
  521. assets: assets,
  522. }
  523. end
  524. # @path [GET] /tickets/import_example
  525. #
  526. # @summary Download of example CSV file.
  527. # @notes The requester have 'admin' permissions to be able to download it.
  528. # @example curl -u 'me@example.com:test' http://localhost:3000/api/v1/tickets/import_example
  529. #
  530. # @response_message 200 File download.
  531. # @response_message 401 Invalid session.
  532. def import_example
  533. permission_check('admin')
  534. csv_string = Ticket.csv_example(
  535. col_sep: ',',
  536. )
  537. send_data(
  538. csv_string,
  539. filename: 'example.csv',
  540. type: 'text/csv',
  541. disposition: 'attachment'
  542. )
  543. end
  544. # @path [POST] /tickets/import
  545. #
  546. # @summary Starts import.
  547. # @notes The requester have 'admin' permissions to be create a new import.
  548. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import?try=true'
  549. # @example curl -u 'me@example.com:test' -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import'
  550. #
  551. # @response_message 201 Import started.
  552. # @response_message 401 Invalid session.
  553. def import_start
  554. permission_check('admin')
  555. if Setting.get('import_mode') != true
  556. raise 'Only can import tickets if system is in import mode.'
  557. end
  558. string = params[:data]
  559. if string.blank? && params[:file].present?
  560. string = params[:file].read.force_encoding('utf-8')
  561. end
  562. raise Exceptions::UnprocessableEntity, 'No source data submitted!' if string.blank?
  563. result = Ticket.csv_import(
  564. string: string,
  565. parse_params: {
  566. col_sep: params[:col_sep] || ',',
  567. },
  568. try: params[:try],
  569. )
  570. render json: result, status: :ok
  571. end
  572. private
  573. def follow_up_possible_check
  574. ticket = Ticket.find(params[:id])
  575. return true if current_user.permissions?('ticket.agent') # agents can always reopen tickets, regardless of group configuration
  576. return true if ticket.group.follow_up_possible != 'new_ticket' # check if the setting for follow_up_possible is disabled
  577. return true if ticket.state.name != 'closed' # check if the ticket state is already closed
  578. raise Exceptions::UnprocessableEntity, 'Cannot follow-up on a closed ticket. Please create a new ticket.'
  579. end
  580. def ticket_all(ticket)
  581. # get attributes to update
  582. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  583. current_user: current_user,
  584. ticket: ticket
  585. )
  586. # get related users
  587. assets = attributes_to_change[:assets]
  588. assets = ticket.assets(assets)
  589. # get related users
  590. article_ids = []
  591. ticket.articles.each do |article|
  592. # ignore internal article if customer is requesting
  593. next if article.internal == true && current_user.permissions?('ticket.customer')
  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. # return result
  606. {
  607. ticket_id: ticket.id,
  608. ticket_article_ids: article_ids,
  609. assets: assets,
  610. links: links,
  611. tags: tags,
  612. form_meta: attributes_to_change[:form_meta],
  613. }
  614. end
  615. end