can_associations.rb 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. # Copyright (C) 2012-2023 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(&:compact).map(&: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. def filter_unauthorized_attributes(attributes)
  192. attributes
  193. end
  194. =begin
  195. reference if association id check
  196. model = Model.find(123)
  197. attributes = model.association_id_validation('attribute_id', value)
  198. returns
  199. true | false
  200. =end
  201. def association_id_validation(attribute_id, value)
  202. return true if value.nil?
  203. attributes.each_key do |key|
  204. next if key != attribute_id
  205. # check if id is assigned
  206. next if !key.end_with?('_id')
  207. key_short = key.chomp('_id')
  208. self.class.reflect_on_all_associations.map do |assoc|
  209. next if assoc.name.to_s != key_short
  210. item = assoc.class_name.constantize
  211. return false if !item.respond_to?(:find_by)
  212. ref_object = item.find_by(id: value)
  213. return false if !ref_object
  214. return true
  215. end
  216. end
  217. true
  218. end
  219. private
  220. def association_attributes_ignored
  221. @association_attributes_ignored ||= self.class.instance_variable_get(:@association_attributes_ignored) || []
  222. end
  223. # methods defined here are going to extend the class, not the instance of it
  224. class_methods do
  225. =begin
  226. serve method to ignore model attribute associations
  227. class Model < ApplicationModel
  228. include AssociationConcern
  229. association_attributes_ignored :users
  230. end
  231. =end
  232. def association_attributes_ignored(*attributes)
  233. @association_attributes_ignored ||= []
  234. @association_attributes_ignored |= attributes
  235. end
  236. =begin
  237. do name/login/email based lookup for associations
  238. params = {
  239. login: 'some login',
  240. firstname: 'some firstname',
  241. lastname: 'some lastname',
  242. email: 'some email',
  243. organization: 'some organization',
  244. roles: ['Agent', 'Admin'],
  245. }
  246. attributes = Model.association_name_to_id_convert(params)
  247. returns
  248. attributes = params # params with possible lookups
  249. attributes = {
  250. login: 'some login',
  251. firstname: 'some firstname',
  252. lastname: 'some lastname',
  253. email: 'some email',
  254. organization_id: 123,
  255. role_ids: [2,1],
  256. }
  257. =end
  258. def association_name_to_id_convert(params)
  259. if params.respond_to?(:permit!)
  260. params = params.permit!.to_h
  261. end
  262. data = {}
  263. params.each do |key, value|
  264. data[key.to_sym] = value
  265. end
  266. data.symbolize_keys!
  267. available_attributes = attribute_names
  268. reflect_on_all_associations.map do |assoc|
  269. assoc_name = assoc.name
  270. value = data[assoc_name]
  271. next if !value # next if we do not have a value
  272. ref_name = "#{assoc_name}_id"
  273. # handle _id values
  274. if available_attributes.include?(ref_name) # if we do have an _id attribute
  275. next if data[ref_name.to_sym] # next if we have already the _id filled
  276. # get association class and do lookup
  277. class_object = assoc.klass
  278. lookup = nil
  279. if class_object == User
  280. if !value.instance_of?(String)
  281. raise Exceptions::UnprocessableEntity, "String is needed as ref value #{value.inspect} for '#{assoc_name}'"
  282. end
  283. if !lookup
  284. lookup = class_object.lookup(login: value)
  285. end
  286. if !lookup
  287. lookup = class_object.lookup(email: value)
  288. end
  289. else
  290. lookup = class_object.lookup(name: value)
  291. end
  292. # complain if we found no reference
  293. if !lookup
  294. raise Exceptions::UnprocessableEntity, "No lookup value found for '#{assoc_name}': #{value.inspect}"
  295. end
  296. # release data value
  297. data.delete(assoc_name)
  298. # remember id reference
  299. data[ref_name.to_sym] = lookup.id
  300. next
  301. end
  302. next if !value.instance_of?(Array)
  303. next if value.blank?
  304. next if !value[0].instance_of?(String)
  305. # handle _ids values
  306. next if !assoc_name.to_s.end_with?('s')
  307. ref_names = "#{assoc_name.to_s.chomp('s')}_ids"
  308. generic_object_tmp = new
  309. next if !generic_object_tmp.respond_to?(ref_names) # if we do have an _ids attribute
  310. next if data[ref_names.to_sym] # next if we have already the _ids filled
  311. # get association class and do lookup
  312. class_object = assoc.klass
  313. lookup_ids = []
  314. value.each do |item|
  315. next if item.blank?
  316. lookup = nil
  317. if class_object == User
  318. if !item.instance_of?(String)
  319. raise Exceptions::UnprocessableEntity, "String is needed in array ref as ref value #{value.inspect} for '#{assoc_name}'"
  320. end
  321. if !lookup
  322. lookup = class_object.lookup(login: item)
  323. end
  324. if !lookup
  325. lookup = class_object.lookup(email: item)
  326. end
  327. else
  328. lookup = class_object.lookup(name: item)
  329. end
  330. # complain if we found no reference
  331. if !lookup
  332. raise Exceptions::UnprocessableEntity, "No lookup value found for '#{assoc_name}': #{item.inspect}"
  333. end
  334. lookup_ids.push lookup.id
  335. end
  336. # release data value
  337. data.delete(assoc_name)
  338. # remember id reference
  339. data[ref_names.to_sym] = lookup_ids
  340. end
  341. data
  342. end
  343. end
  344. end