tickets_controller.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class TicketsController < ApplicationController
  3. include CreatesTicketArticles
  4. include ClonesTicketArticleAttachments
  5. include ChecksUserAttributesByCurrentUserPermission
  6. include CanPaginate
  7. prepend_before_action -> { authorize! }, only: %i[create 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. paginate_with(max: 100)
  12. tickets = TicketPolicy::ReadScope.new(current_user).resolve
  13. .reorder(id: :asc)
  14. .offset(pagination.offset)
  15. .limit(pagination.limit)
  16. if response_expand?
  17. list = tickets.map(&:attributes_with_association_names)
  18. render json: list, status: :ok
  19. return
  20. end
  21. if response_full?
  22. assets = {}
  23. item_ids = []
  24. tickets.each do |item|
  25. item_ids.push item.id
  26. assets = item.assets(assets)
  27. end
  28. render json: {
  29. record_ids: item_ids,
  30. assets: assets,
  31. }, status: :ok
  32. return
  33. end
  34. render json: tickets
  35. end
  36. # GET /api/v1/tickets/1
  37. def show
  38. ticket = Ticket.find(params[:id])
  39. authorize!(ticket)
  40. auto_assign_ticket(ticket)
  41. if response_expand?
  42. result = ticket.attributes_with_association_names
  43. render json: result, status: :ok
  44. return
  45. end
  46. if response_full?
  47. full = Ticket.full(params[:id])
  48. render json: full
  49. return
  50. end
  51. if response_all?
  52. render json: Ticket::AssetsAll.new(current_user, ticket).all_assets
  53. return
  54. end
  55. render json: ticket
  56. end
  57. def auto_assign_ticket(ticket)
  58. return if params[:auto_assign].blank?
  59. ticket.auto_assign(current_user)
  60. end
  61. # POST /api/v1/tickets
  62. def create
  63. ticket = nil
  64. Transaction.execute do # rubocop:disable Metrics/BlockLength
  65. customer = {}
  66. if params[:customer].instance_of?(ActionController::Parameters)
  67. customer = params[:customer]
  68. params.delete(:customer)
  69. end
  70. if (shared_draft_id = params[:shared_draft_id])
  71. shared_draft = Ticket::SharedDraftStart.find_by id: shared_draft_id
  72. if shared_draft && (shared_draft.group_id.to_s != params[:group_id]&.to_s || !shared_draft.group.shared_drafts?)
  73. raise Exceptions::UnprocessableEntity, __('Shared draft cannot be selected for this ticket.')
  74. end
  75. shared_draft&.destroy
  76. end
  77. # Prevent direct access to checklist via API
  78. # Otherwise users may get unauthorized access to checklists of other tickets
  79. params.delete(:checklist)
  80. params.delete(:checklist_id)
  81. clean_params = Ticket.association_name_to_id_convert(params)
  82. # overwrite params
  83. if !current_user.permissions?('ticket.agent')
  84. %i[owner owner_id customer customer_id preferences].each do |key|
  85. clean_params.delete(key)
  86. end
  87. clean_params[:customer_id] = current_user.id
  88. end
  89. # The parameter :customer_id is 'abused' in cases where it is not an integer, but a string like
  90. # 'guess:customers.email@domain.cm' which implies that the customer should be looked up.
  91. if clean_params[:customer_id].is_a?(String) && clean_params[:customer_id] =~ %r{^guess:(.+?)$}
  92. email_address = $1
  93. email_address_validation = EmailAddressValidation.new(email_address)
  94. if !email_address_validation.valid?
  95. render json: { error: "Invalid email '#{email_address}' of customer" }, status: :unprocessable_entity
  96. return
  97. end
  98. local_customer = User.find_by(email: email_address.downcase)
  99. if !local_customer
  100. role_ids = Role.signup_role_ids
  101. local_customer = User.create(
  102. firstname: '',
  103. lastname: '',
  104. email: email_address,
  105. password: '',
  106. active: true,
  107. role_ids: role_ids,
  108. )
  109. end
  110. clean_params[:customer_id] = local_customer.id
  111. end
  112. # try to create customer if needed
  113. if clean_params[:customer_id].blank? && customer.present?
  114. check_attributes_by_current_user_permission(customer)
  115. clean_customer = User.association_name_to_id_convert(customer)
  116. local_customer = nil
  117. if !local_customer && clean_customer[:id].present?
  118. local_customer = User.find_by(id: clean_customer[:id])
  119. end
  120. if !local_customer && clean_customer[:email].present?
  121. local_customer = User.find_by(email: clean_customer[:email].downcase)
  122. end
  123. if !local_customer && clean_customer[:login].present?
  124. local_customer = User.find_by(login: clean_customer[:login].downcase)
  125. end
  126. if !local_customer
  127. role_ids = Role.signup_role_ids
  128. local_customer = User.new(clean_customer)
  129. local_customer.role_ids = role_ids
  130. local_customer.save!
  131. end
  132. clean_params[:customer_id] = local_customer.id
  133. end
  134. clean_params = Ticket.param_cleanup(clean_params, true)
  135. clean_params[:screen] = 'create_middle'
  136. ticket = Ticket.new(clean_params)
  137. authorize!(ticket, :create?)
  138. # create ticket
  139. ticket.save!
  140. # create tags if given
  141. if params[:tags].present?
  142. tags = params[:tags].split(',').map(&:strip)
  143. tags.each do |tag|
  144. next if !::Tag.tag_allowed?(name: tag, user_id: UserInfo.current_user_id)
  145. ticket.tag_add(tag)
  146. end
  147. end
  148. # This mentions handling is used by custom API calls only
  149. # Mentions created in UI are handled by Ticket::Article#check_mentions
  150. if params[:mentions].present?
  151. authorize!(ticket, :create_mentions?)
  152. Array(params[:mentions]).each do |user_id|
  153. Mention.subscribe! ticket, User.find(user_id)
  154. end
  155. end
  156. # create article if given
  157. if params[:article]
  158. article_create(ticket, params[:article])
  159. end
  160. # create links (e. g. in case of ticket split)
  161. # links: {
  162. # Ticket: {
  163. # parent: [ticket_id1, ticket_id2, ...]
  164. # normal: [ticket_id1, ticket_id2, ...]
  165. # child: [ticket_id1, ticket_id2, ...]
  166. # },
  167. # }
  168. if params[:links].present?
  169. link = params[:links].permit!.to_h
  170. raise Exceptions::UnprocessableEntity, __('Invalid link structure') if !link.is_a? Hash
  171. link.each do |target_object, link_types_with_object_ids|
  172. raise Exceptions::UnprocessableEntity, __('Invalid link structure (Object)') if !link_types_with_object_ids.is_a? Hash
  173. link_types_with_object_ids.each do |link_type, object_ids|
  174. raise Exceptions::UnprocessableEntity, __('Invalid link structure (Object → LinkType)') if !object_ids.is_a? Array
  175. object_ids.each do |local_object_id|
  176. link = Link.add(
  177. link_type: link_type,
  178. link_object_target: target_object,
  179. link_object_target_value: local_object_id,
  180. link_object_source: 'Ticket',
  181. link_object_source_value: ticket.id,
  182. )
  183. end
  184. end
  185. end
  186. end
  187. end
  188. if response_expand?
  189. result = ticket.reload.attributes_with_association_names
  190. render json: result, status: :created
  191. return
  192. end
  193. if response_full?
  194. full = Ticket.full(ticket.id)
  195. render json: full, status: :created
  196. return
  197. end
  198. if response_all?
  199. render json: Ticket::AssetsAll.new(current_user, ticket.reload).all_assets, status: :created
  200. return
  201. end
  202. render json: ticket.reload.attributes_with_association_ids, status: :created
  203. end
  204. # PUT /api/v1/tickets/1
  205. def update
  206. ticket = Ticket.find(params[:id])
  207. authorize!(ticket, :follow_up?)
  208. # Prevent direct access to checklist via API
  209. # Otherwise users may get unauthorized access to checklists of other tickets
  210. params.delete(:checklist)
  211. params.delete(:checklist_id)
  212. clean_params = Ticket.association_name_to_id_convert(params)
  213. clean_params = Ticket.param_cleanup(clean_params, true)
  214. # only apply preferences changes (keep not updated keys/values)
  215. clean_params = ticket.param_preferences_merge(clean_params)
  216. clean_params[:screen] = 'edit'
  217. # disable changes on ticket number
  218. clean_params.delete('number')
  219. # overwrite params
  220. if !current_user.permissions?('ticket.agent')
  221. %i[owner owner_id customer customer_id organization organization_id preferences].each do |key|
  222. clean_params.delete(key)
  223. end
  224. end
  225. ticket.with_lock do
  226. ticket.update!(clean_params)
  227. if params[:article].present?
  228. if (shared_draft_id = params[:article][:shared_draft_id])
  229. shared_draft = Ticket::SharedDraftZoom.find_by id: shared_draft_id
  230. if shared_draft && shared_draft.ticket != ticket
  231. raise Exceptions::UnprocessableEntity, __('Shared draft cannot be selected for this ticket.')
  232. end
  233. shared_draft&.destroy
  234. end
  235. article_create(ticket, params[:article])
  236. end
  237. end
  238. if response_expand?
  239. result = ticket.reload.attributes_with_association_names
  240. render json: result, status: :ok
  241. return
  242. end
  243. if response_full?
  244. full = Ticket.full(params[:id])
  245. render json: full, status: :ok
  246. return
  247. end
  248. if response_all?
  249. render json: Ticket::AssetsAll.new(current_user, ticket.reload).all_assets, status: :ok
  250. return
  251. end
  252. render json: ticket.reload.attributes_with_association_ids, status: :ok
  253. end
  254. # DELETE /api/v1/tickets/1
  255. def destroy
  256. ticket = Ticket.find(params[:id])
  257. authorize!(ticket)
  258. ticket.destroy!
  259. head :ok
  260. end
  261. # GET /api/v1/ticket_customer
  262. # GET /api/v1/tickets_customer
  263. def ticket_customer
  264. # return result
  265. result = Ticket::ScreenOptions.list_by_customer(
  266. current_user: current_user,
  267. customer_id: params[:customer_id],
  268. limit: 15,
  269. )
  270. render json: result
  271. end
  272. # GET /api/v1/ticket_history/1
  273. def ticket_history
  274. # get ticket data
  275. ticket = Ticket.find(params[:id])
  276. authorize!(ticket, :show?)
  277. # get history of ticket
  278. render json: ticket.history_get(true)
  279. end
  280. # GET /api/v1/ticket_related/1
  281. def ticket_related
  282. ticket = Ticket.find(params[:ticket_id])
  283. assets = ticket.assets({})
  284. tickets = TicketPolicy::ReadScope.new(current_user).resolve
  285. .where(
  286. customer_id: ticket.customer_id,
  287. state_id: Ticket::State.by_category(:open).select(:id),
  288. )
  289. .where.not(id: ticket.id)
  290. .reorder(created_at: :desc)
  291. .limit(6)
  292. # if we do not have open related tickets, search for any tickets
  293. tickets ||= TicketPolicy::ReadScope.new(current_user).resolve
  294. .where(customer_id: ticket.customer_id)
  295. .where.not(state_id: Ticket::State.by_category_ids(:merged))
  296. .where.not(id: ticket.id)
  297. .reorder(created_at: :desc)
  298. .limit(6)
  299. # get related assets
  300. ticket_ids_by_customer = []
  301. tickets.each do |ticket_list|
  302. ticket_ids_by_customer.push ticket_list.id
  303. assets = ticket_list.assets(assets)
  304. end
  305. ticket_ids_recent_viewed = []
  306. recent_views = RecentView.list(current_user, 8, 'Ticket')
  307. recent_views.each do |recent_view|
  308. next if recent_view.object.name != 'Ticket'
  309. next if recent_view.o_id == ticket.id
  310. ticket_ids_recent_viewed.push recent_view.o_id
  311. recent_view_ticket = Ticket.find(recent_view.o_id)
  312. assets = recent_view_ticket.assets(assets)
  313. end
  314. # return result
  315. render json: {
  316. assets: assets,
  317. ticket_ids_by_customer: ticket_ids_by_customer,
  318. ticket_ids_recent_viewed: ticket_ids_recent_viewed,
  319. }
  320. end
  321. # GET /api/v1/ticket_recent
  322. def ticket_recent
  323. ticket_ids = RecentView.list(current_user, 10, Ticket.name).map(&:o_id)
  324. tickets = ticket_ids.map { |elem| Ticket.lookup(id: elem) }
  325. assets = ApplicationModel::CanAssets.reduce(tickets)
  326. render json: {
  327. assets: assets,
  328. ticket_ids_recent_viewed: ticket_ids
  329. }
  330. end
  331. # PUT /api/v1/ticket_merge/1/1
  332. def ticket_merge
  333. # check target ticket
  334. target_ticket = Ticket.find_by(number: params[:target_ticket_number])
  335. if !target_ticket
  336. render json: {
  337. result: 'failed',
  338. message: __('The target ticket number could not be found.'),
  339. }
  340. return
  341. end
  342. # check source ticket
  343. source_ticket = Ticket.find_by(id: params[:source_ticket_id])
  344. if !source_ticket
  345. render json: {
  346. result: 'failed',
  347. message: __('The source ticket could not be found.'),
  348. }
  349. return
  350. end
  351. # merge ticket
  352. Service::Ticket::Merge.new(current_user:).execute(source_ticket:, target_ticket:)
  353. # return result
  354. render json: {
  355. result: 'success',
  356. target_ticket: target_ticket.attributes,
  357. source_ticket: source_ticket.attributes,
  358. }
  359. end
  360. # GET /api/v1/ticket_split
  361. def ticket_split
  362. ticket = Ticket.find(params[:ticket_id])
  363. authorize!(ticket, :show?)
  364. assets = ticket.assets({})
  365. article = Ticket::Article.find(params[:article_id])
  366. authorize!(article.ticket, :show?)
  367. assets = article.assets(assets)
  368. render json: {
  369. assets: assets,
  370. attachments: article_attachments_clone(article),
  371. }
  372. end
  373. # GET /api/v1/ticket_create
  374. def ticket_create
  375. # get attributes to update
  376. attributes_to_change = Ticket::ScreenOptions.attributes_to_change(
  377. view: 'ticket_create',
  378. screen: 'create_middle',
  379. current_user: current_user,
  380. )
  381. render json: attributes_to_change
  382. end
  383. # GET /api/v1/tickets/search
  384. def search
  385. model_search_render(Ticket, params)
  386. end
  387. # GET /api/v1/ticket_stats
  388. def stats
  389. if !params[:user_id] && !params[:organization_id]
  390. raise __('Need user_id or organization_id as param')
  391. end
  392. # return result
  393. render json: Ticket::Stats.new(current_user: current_user, user_id: params[:user_id], organization_id: params[:organization_id], assets: {}).list_stats
  394. end
  395. # @path [GET] /tickets/import_example
  396. #
  397. # @summary Download of example CSV file.
  398. # @notes The requester have 'admin' permissions to be able to download it.
  399. # @example curl -u #{login}:#{password} http://localhost:3000/api/v1/tickets/import_example
  400. #
  401. # @response_message 200 File download.
  402. # @response_message 403 Forbidden / Invalid session.
  403. def import_example
  404. csv_string = Ticket.csv_example(
  405. col_sep: ',',
  406. )
  407. send_data(
  408. csv_string,
  409. filename: 'example.csv',
  410. type: 'text/csv',
  411. disposition: 'attachment'
  412. )
  413. end
  414. # @path [POST] /tickets/import
  415. #
  416. # @summary Starts import.
  417. # @notes The requester have 'admin' permissions to be create a new import.
  418. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import?try=true'
  419. # @example curl -u #{login}:#{password} -F 'file=@/path/to/file/tickets.csv' 'https://your.zammad/api/v1/tickets/import'
  420. #
  421. # @response_message 201 Import started.
  422. # @response_message 403 Forbidden / Invalid session.
  423. def import_start
  424. if Setting.get('import_mode') != true
  425. raise __('Tickets can only be imported if system is in import mode.')
  426. end
  427. string = params[:data]
  428. if string.blank? && params[:file].present?
  429. string = params[:file].read.force_encoding('utf-8')
  430. end
  431. raise Exceptions::UnprocessableEntity, __('No source data submitted!') if string.blank?
  432. result = Ticket.csv_import(
  433. string: string,
  434. parse_params: {
  435. col_sep: params[:col_sep] || ',',
  436. },
  437. try: params[:try],
  438. )
  439. render json: result, status: :ok
  440. end
  441. end