can_associations.rb 11 KB

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