can_associations.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module ApplicationModel::CanAssociations
  3. extend ActiveSupport::Concern
  4. =begin
  5. set relations of model based on params
  6. model = Model.find(1)
  7. result = model.associations_from_param(params)
  8. returns
  9. result = true|false
  10. =end
  11. def associations_from_param(params)
  12. # special handling for group access association
  13. {
  14. groups: :group_names_access_map=,
  15. group_ids: :group_ids_access_map=
  16. }.each do |param, setter|
  17. next if !params.key?(param)
  18. map = params[param]
  19. next if !respond_to?(setter)
  20. send(setter, map)
  21. end
  22. # set relations by id/verify if ref exists
  23. self.class.reflect_on_all_associations.map do |assoc|
  24. assoc_name = assoc.name
  25. next if association_attributes_ignored.include?(assoc_name)
  26. real_ids = "#{assoc_name[0, assoc_name.length - 1]}_ids"
  27. real_ids = real_ids.to_sym
  28. next if !params.key?(real_ids)
  29. list_of_items = params[real_ids]
  30. if !params[real_ids].instance_of?(Array)
  31. list_of_items = [ params[real_ids] ]
  32. end
  33. list = []
  34. list_of_items.each do |item_id|
  35. next if !item_id
  36. lookup = assoc.klass.lookup(id: item_id)
  37. # complain if we found no reference
  38. if !lookup
  39. raise Exceptions::UnprocessableEntity, "No value found for '#{assoc_name}' with id #{item_id.inspect}"
  40. end
  41. list.push item_id
  42. end
  43. next if Array(list).sort == Array(send(real_ids)).sort
  44. send(:"#{real_ids}=", list)
  45. self.updated_at = Time.zone.now
  46. end
  47. # set relations by name/lookup
  48. self.class.reflect_on_all_associations.map do |assoc|
  49. assoc_name = assoc.name
  50. next if association_attributes_ignored.include?(assoc_name)
  51. real_ids = "#{assoc_name[0, assoc_name.length - 1]}_ids"
  52. next if !respond_to?(real_ids)
  53. real_values = "#{assoc_name[0, assoc_name.length - 1]}s"
  54. real_values = real_values.to_sym
  55. next if !respond_to?(real_values)
  56. next if !params[real_values]
  57. if params[real_values].instance_of?(String) || params[real_values].instance_of?(Integer) || params[real_values].instance_of?(Float)
  58. params[real_values] = [params[real_values]]
  59. end
  60. next if !params[real_values].instance_of?(Array)
  61. list = []
  62. class_object = assoc.klass
  63. params[real_values].each do |value|
  64. next if value.blank?
  65. lookup = nil
  66. if class_object == User
  67. if !lookup
  68. lookup = class_object.lookup(login: value)
  69. end
  70. if !lookup
  71. lookup = class_object.lookup(email: value)
  72. end
  73. else
  74. lookup = class_object.lookup(name: value)
  75. end
  76. # complain if we found no reference
  77. if !lookup
  78. raise Exceptions::UnprocessableEntity, "No lookup value found for '#{assoc_name}': #{value.inspect}"
  79. end
  80. list.push lookup.id
  81. end
  82. next if Array(list).sort == Array(send(real_ids)).sort
  83. send(:"#{real_ids}=", list)
  84. self.updated_at = Time.zone.now
  85. end
  86. end
  87. =begin
  88. get relations of model based on params
  89. model = Model.find(1)
  90. attributes = model.attributes_with_association_ids
  91. returns
  92. hash with attributes and association ids
  93. =end
  94. def attributes_with_association_ids
  95. key = "#{self.class}::aws::#{id}"
  96. cache = Rails.cache.read(key)
  97. return filter_unauthorized_attributes(cache) if cache && cache['updated_at'] == try(:updated_at)
  98. attributes = self.attributes
  99. relevant = %i[has_and_belongs_to_many has_many]
  100. eager_load = []
  101. pluck = []
  102. keys = []
  103. self.class.reflect_on_all_associations.each do |assoc|
  104. next if relevant.exclude?(assoc.macro)
  105. assoc_name = assoc.name
  106. next if association_attributes_ignored.include?(assoc_name)
  107. eager_load.push(assoc_name)
  108. pluck.push(Arel.sql("#{ActiveRecord::Base.connection.quote_table_name(assoc.table_name)}.id AS #{ActiveRecord::Base.connection.quote_table_name(assoc_name)}"))
  109. keys.push("#{assoc_name.to_s.singularize}_ids")
  110. end
  111. if eager_load.present?
  112. ids = self.class.eager_load(eager_load)
  113. .where(id: id)
  114. .pluck(*pluck)
  115. if keys.size > 1
  116. values = ids.transpose.map { |x| x.compact.uniq }
  117. attributes.merge!(keys.zip(values).to_h)
  118. else
  119. attributes[ keys.first ] = ids.compact
  120. end
  121. end
  122. # special handling for group access associations
  123. if respond_to?(:group_ids_access_map)
  124. attributes['group_ids'] = send(:group_ids_access_map)
  125. end
  126. filter_attributes(attributes)
  127. Rails.cache.write(key, attributes)
  128. filter_unauthorized_attributes(attributes)
  129. end
  130. =begin
  131. get relation name of model based on params
  132. model = Model.find(1)
  133. attributes = model.attributes_with_association_names
  134. returns
  135. hash with attributes, association ids, association names and relation name
  136. =end
  137. def attributes_with_association_names(empty_keys: false)
  138. # get relations
  139. attributes = attributes_with_association_ids
  140. self.class.reflect_on_all_associations.map do |assoc|
  141. next if !respond_to?(assoc.name)
  142. next if association_attributes_ignored.include?(assoc.name)
  143. ref = send(assoc.name)
  144. if empty_keys
  145. attributes[assoc.name.to_s] = nil
  146. end
  147. next if !ref
  148. if ref.respond_to?(:first)
  149. attributes[assoc.name.to_s] = []
  150. ref.each do |item|
  151. if item[:login]
  152. attributes[assoc.name.to_s].push item[:login]
  153. next
  154. end
  155. next if !item[:name]
  156. attributes[assoc.name.to_s].push item[:name]
  157. end
  158. if ref.count.positive? && attributes[assoc.name.to_s].blank?
  159. attributes.delete(assoc.name.to_s)
  160. end
  161. next
  162. end
  163. if ref[:login]
  164. attributes[assoc.name.to_s] = ref[:login]
  165. next
  166. end
  167. next if !ref[:name]
  168. attributes[assoc.name.to_s] = ref[:name]
  169. end
  170. # special handling for group access associations
  171. if respond_to?(:group_names_access_map)
  172. attributes['groups'] = send(:group_names_access_map)
  173. end
  174. # fill created_by/updated_by
  175. {
  176. 'created_by_id' => 'created_by',
  177. 'updated_by_id' => 'updated_by',
  178. }.each do |source, destination|
  179. next if !attributes[source]
  180. user = User.lookup(id: attributes[source])
  181. next if !user
  182. attributes[destination] = user.login
  183. end
  184. filter_attributes(attributes)
  185. filter_unauthorized_attributes(attributes)
  186. end
  187. def filter_attributes(attributes)
  188. # remove forbidden attributes
  189. attributes.except!('password', 'token', 'tokens', 'token_ids')
  190. end
  191. # overwrite this method in derived classes to filter attributes, e.g. app/models/user/assets.rb
  192. def filter_unauthorized_attributes(attributes)
  193. attributes
  194. end
  195. =begin
  196. reference if association id check
  197. model = Model.find(123)
  198. attributes = model.association_id_validation('attribute_id', value)
  199. returns
  200. true | false
  201. =end
  202. def association_id_validation(attribute_id, value)
  203. return true if value.nil?
  204. attributes.each_key do |key|
  205. next if key != attribute_id
  206. # check if id is assigned
  207. next if !key.end_with?('_id')
  208. key_short = key.chomp('_id')
  209. self.class.reflect_on_all_associations.map do |assoc|
  210. next if assoc.name.to_s != key_short
  211. item = assoc.class_name.constantize
  212. return false if !item.respond_to?(:find_by)
  213. ref_object = item.find_by(id: value)
  214. return false if !ref_object
  215. return true
  216. end
  217. end
  218. true
  219. end
  220. private
  221. def association_attributes_ignored
  222. @association_attributes_ignored ||= self.class.instance_variable_get(:@association_attributes_ignored) || []
  223. end
  224. # methods defined here are going to extend the class, not the instance of it
  225. class_methods do
  226. =begin
  227. serve method to ignore model attribute associations
  228. class Model < ApplicationModel
  229. include AssociationConcern
  230. association_attributes_ignored :users
  231. end
  232. =end
  233. def association_attributes_ignored(*attributes)
  234. @association_attributes_ignored ||= []
  235. @association_attributes_ignored |= attributes
  236. end
  237. =begin
  238. do name/login/email based lookup for associations
  239. params = {
  240. login: 'some login',
  241. firstname: 'some firstname',
  242. lastname: 'some lastname',
  243. email: 'some email',
  244. organization: 'some organization',
  245. roles: ['Agent', 'Admin'],
  246. }
  247. attributes = Model.association_name_to_id_convert(params)
  248. returns
  249. attributes = params # params with possible lookups
  250. attributes = {
  251. login: 'some login',
  252. firstname: 'some firstname',
  253. lastname: 'some lastname',
  254. email: 'some email',
  255. organization_id: 123,
  256. role_ids: [2,1],
  257. }
  258. =end
  259. def association_name_to_id_convert(params)
  260. if params.respond_to?(:permit!)
  261. params = params.permit!.to_h
  262. end
  263. data = {}
  264. params.each do |key, value|
  265. data[key.to_sym] = value
  266. end
  267. data.symbolize_keys!
  268. available_attributes = attribute_names
  269. reflect_on_all_associations.map do |assoc|
  270. assoc_name = assoc.name
  271. value = data[assoc_name]
  272. next if !value # next if we do not have a value
  273. ref_name = "#{assoc_name}_id"
  274. # handle _id values
  275. if available_attributes.include?(ref_name) # if we do have an _id attribute
  276. next if data[ref_name.to_sym] # next if we have already the _id filled
  277. # get association class and do lookup
  278. class_object = assoc.klass
  279. lookup = nil
  280. if class_object == User
  281. if !value.instance_of?(String)
  282. raise Exceptions::UnprocessableEntity, "String is needed as ref value #{value.inspect} for '#{assoc_name}'"
  283. end
  284. if !lookup
  285. lookup = class_object.lookup(login: value)
  286. end
  287. if !lookup
  288. lookup = class_object.lookup(email: value)
  289. end
  290. else
  291. lookup = class_object.lookup(name: value)
  292. end
  293. # complain if we found no reference
  294. if !lookup
  295. raise Exceptions::UnprocessableEntity, "No lookup value found for '#{assoc_name}': #{value.inspect}"
  296. end
  297. # release data value
  298. data.delete(assoc_name)
  299. # remember id reference
  300. data[ref_name.to_sym] = lookup.id
  301. next
  302. end
  303. next if !value.instance_of?(Array)
  304. next if value.blank?
  305. next if !value[0].instance_of?(String)
  306. # handle _ids values
  307. next if !assoc_name.to_s.end_with?('s')
  308. ref_names = "#{assoc_name.to_s.chomp('s')}_ids"
  309. generic_object_tmp = new
  310. next if !generic_object_tmp.respond_to?(ref_names) # if we do have an _ids attribute
  311. next if data[ref_names.to_sym] # next if we have already the _ids filled
  312. # get association class and do lookup
  313. class_object = assoc.klass
  314. lookup_ids = []
  315. value.each do |item|
  316. next if item.blank?
  317. lookup = nil
  318. if class_object == User
  319. if !item.instance_of?(String)
  320. raise Exceptions::UnprocessableEntity, "String is needed in array ref as ref value #{value.inspect} for '#{assoc_name}'"
  321. end
  322. if !lookup
  323. lookup = class_object.lookup(login: item)
  324. end
  325. if !lookup
  326. lookup = class_object.lookup(email: item)
  327. end
  328. else
  329. lookup = class_object.lookup(name: item)
  330. end
  331. # complain if we found no reference
  332. if !lookup
  333. raise Exceptions::UnprocessableEntity, "No lookup value found for '#{assoc_name}': #{item.inspect}"
  334. end
  335. lookup_ids.push lookup.id
  336. end
  337. # release data value
  338. data.delete(assoc_name)
  339. # remember id reference
  340. data[ref_names.to_sym] = lookup_ids
  341. end
  342. data
  343. end
  344. end
  345. end