transaction.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Transaction
  3. attr_reader :options
  4. attr_accessor :original_user_id, :original_interface_handle, :original_interface_context
  5. def initialize(options = {})
  6. @options = options
  7. end
  8. def execute
  9. start_execute
  10. ActiveRecord::Base.transaction do
  11. start_transaction
  12. yield
  13. ensure
  14. finish_transaction
  15. end
  16. ensure
  17. finish_execute
  18. end
  19. def self.execute(options = {}, &)
  20. Transaction.new(options).execute(&)
  21. end
  22. private
  23. def start_execute
  24. reset_user_id_start
  25. bulk_import_start
  26. interface_handle_start
  27. interface_context_start
  28. end
  29. def start_transaction
  30. PushMessages.init
  31. end
  32. def finish_execute
  33. reset_user_id_finish
  34. bulk_import_finish
  35. end
  36. def finish_transaction
  37. interface_handle_finish
  38. interface_context_finish
  39. TransactionDispatcher.commit(options)
  40. PushMessages.finish
  41. end
  42. def reset_user_id?
  43. options[:reset_user_id] == true
  44. end
  45. def reset_user_id_start
  46. return if !reset_user_id?
  47. self.original_user_id = UserInfo.current_user_id
  48. UserInfo.current_user_id = 1
  49. end
  50. def reset_user_id_finish
  51. return if !reset_user_id?
  52. UserInfo.current_user_id = original_user_id
  53. end
  54. def bulk_import?
  55. options[:bulk] == true
  56. end
  57. def bulk_import_start
  58. return if !bulk_import?
  59. BulkImportInfo.enable
  60. end
  61. def bulk_import_finish
  62. return if !bulk_import?
  63. BulkImportInfo.disable
  64. end
  65. def interface_handle?
  66. options[:interface_handle].present?
  67. end
  68. def interface_handle_start
  69. return if !interface_handle?
  70. self.original_interface_handle = ApplicationHandleInfo.current
  71. ApplicationHandleInfo.current = options[:interface_handle]
  72. end
  73. def interface_handle_finish
  74. return if !interface_handle?
  75. ApplicationHandleInfo.current = original_interface_handle
  76. end
  77. def interface_context?
  78. options[:context].present?
  79. end
  80. def interface_context_start
  81. return if !interface_context?
  82. self.original_interface_context = ApplicationHandleInfo.context
  83. ApplicationHandleInfo.context = options[:context]
  84. end
  85. def interface_context_finish
  86. return if !interface_context?
  87. ApplicationHandleInfo.context = original_interface_context
  88. end
  89. end