tickets_controller.rb 19 KB

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