tickets_controller.rb 19 KB

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