attribute.rb 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. class ObjectManager::Attribute < ApplicationModel
  2. include ChecksClientNotification
  3. include CanSeed
  4. DATA_TYPES = %w[
  5. input
  6. user_autocompletion
  7. checkbox
  8. select
  9. tree_select
  10. datetime
  11. date
  12. tag
  13. richtext
  14. textarea
  15. integer
  16. autocompletion_ajax
  17. boolean
  18. user_permission
  19. active
  20. ].freeze
  21. self.table_name = 'object_manager_attributes'
  22. belongs_to :object_lookup, optional: true
  23. validates :name, presence: true
  24. validates :data_type, inclusion: { in: DATA_TYPES, msg: '%{value} is not a valid data type' }
  25. validate :data_option_must_have_appropriate_values
  26. validate :data_type_must_not_change, on: :update
  27. store :screens
  28. store :data_option
  29. store :data_option_new
  30. before_validation :set_base_options
  31. =begin
  32. list of all attributes
  33. result = ObjectManager::Attribute.list_full
  34. result = [
  35. {
  36. name: 'some name',
  37. display: '...',
  38. }.
  39. ],
  40. =end
  41. def self.list_full
  42. result = ObjectManager::Attribute.all.order('position ASC, name ASC')
  43. references = ObjectManager::Attribute.attribute_to_references_hash
  44. attributes = []
  45. result.each do |item|
  46. attribute = item.attributes
  47. attribute[:object] = ObjectLookup.by_id(item.object_lookup_id)
  48. attribute.delete('object_lookup_id')
  49. # an attribute is deletable if it is both editable and not referenced by other Objects (Triggers, Overviews, Schedulers)
  50. deletable = true
  51. not_deletable_reason = ''
  52. if ObjectManager::Attribute.attribute_used_by_references?(attribute[:object], attribute['name'], references)
  53. deletable = false
  54. not_deletable_reason = ObjectManager::Attribute.attribute_used_by_references_humaniced(attribute[:object], attribute['name'], references)
  55. end
  56. attribute[:deletable] = attribute['editable'] && deletable == true
  57. if not_deletable_reason.present?
  58. attribute[:not_deletable_reason] = "This attribute is referenced by #{not_deletable_reason} and thus cannot be deleted!"
  59. end
  60. attributes.push attribute
  61. end
  62. attributes
  63. end
  64. =begin
  65. add a new attribute entry for an object
  66. ObjectManager::Attribute.add(
  67. object: 'Ticket',
  68. name: 'group_id',
  69. display: 'Group',
  70. data_type: 'select',
  71. data_option: {
  72. relation: 'Group',
  73. relation_condition: { access: 'full' },
  74. multiple: false,
  75. null: true,
  76. translate: false,
  77. },
  78. active: true,
  79. screens: {
  80. create: {
  81. '-all-' => {
  82. required: true,
  83. },
  84. },
  85. edit: {
  86. 'ticket.agent' => {
  87. required: true,
  88. },
  89. },
  90. },
  91. position: 20,
  92. created_by_id: 1,
  93. updated_by_id: 1,
  94. created_at: '2014-06-04 10:00:00',
  95. updated_at: '2014-06-04 10:00:00',
  96. force: true
  97. editable: false,
  98. to_migrate: false,
  99. to_create: false,
  100. to_delete: false,
  101. to_config: false,
  102. )
  103. preserved name are
  104. /(_id|_ids)$/
  105. possible types
  106. # input
  107. data_type: 'input',
  108. data_option: {
  109. default: '',
  110. type: 'text', # text|email|url|tel
  111. maxlength: 200,
  112. null: true,
  113. note: 'some additional comment', # optional
  114. link_template: '', # optional
  115. },
  116. # select
  117. data_type: 'select',
  118. data_option: {
  119. default: 'aa',
  120. options: {
  121. 'aa' => 'aa (comment)',
  122. 'bb' => 'bb (comment)',
  123. },
  124. maxlength: 200,
  125. nulloption: true,
  126. null: false,
  127. multiple: false, # currently only "false" supported
  128. translate: true, # optional
  129. note: 'some additional comment', # optional
  130. link_template: '', # optional
  131. },
  132. # tree_select
  133. data_type: 'tree_select',
  134. data_option: {
  135. default: 'aa',
  136. options: [
  137. {
  138. 'value' => 'aa',
  139. 'name' => 'aa (comment)',
  140. 'children' => [
  141. {
  142. 'value' => 'aaa',
  143. 'name' => 'aaa (comment)',
  144. },
  145. {
  146. 'value' => 'aab',
  147. 'name' => 'aab (comment)',
  148. },
  149. {
  150. 'value' => 'aac',
  151. 'name' => 'aac (comment)',
  152. },
  153. ]
  154. },
  155. {
  156. 'value' => 'bb',
  157. 'name' => 'bb (comment)',
  158. 'children' => [
  159. {
  160. 'value' => 'bba',
  161. 'name' => 'aaa (comment)',
  162. },
  163. {
  164. 'value' => 'bbb',
  165. 'name' => 'bbb (comment)',
  166. },
  167. {
  168. 'value' => 'bbc',
  169. 'name' => 'bbc (comment)',
  170. },
  171. ]
  172. },
  173. ],
  174. maxlength: 200,
  175. nulloption: true,
  176. null: false,
  177. multiple: false, # currently only "false" supported
  178. translate: true, # optional
  179. note: 'some additional comment', # optional
  180. },
  181. # checkbox
  182. data_type: 'checkbox',
  183. data_option: {
  184. default: 'aa',
  185. options: {
  186. 'aa' => 'aa (comment)',
  187. 'bb' => 'bb (comment)',
  188. },
  189. null: false,
  190. translate: true, # optional
  191. note: 'some additional comment', # optional
  192. },
  193. # integer
  194. data_type: 'integer',
  195. data_option: {
  196. default: 5,
  197. min: 15,
  198. max: 999,
  199. null: false,
  200. note: 'some additional comment', # optional
  201. },
  202. # boolean
  203. data_type: 'boolean',
  204. data_option: {
  205. default: true,
  206. options: {
  207. true => 'aa',
  208. false => 'bb',
  209. },
  210. null: false,
  211. translate: true, # optional
  212. note: 'some additional comment', # optional
  213. },
  214. # datetime
  215. data_type: 'datetime',
  216. data_option: {
  217. future: true, # true|false
  218. past: true, # true|false
  219. diff: 12, # in hours
  220. null: false,
  221. note: 'some additional comment', # optional
  222. },
  223. # date
  224. data_type: 'date',
  225. data_option: {
  226. future: true, # true|false
  227. past: true, # true|false
  228. diff: 15, # in days
  229. null: false,
  230. note: 'some additional comment', # optional
  231. },
  232. # textarea
  233. data_type: 'textarea',
  234. data_option: {
  235. default: '',
  236. rows: 15,
  237. null: false,
  238. note: 'some additional comment', # optional
  239. },
  240. # richtext
  241. data_type: 'richtext',
  242. data_option: {
  243. default: '',
  244. null: false,
  245. note: 'some additional comment', # optional
  246. },
  247. =end
  248. def self.add(data)
  249. force = data[:force]
  250. data.delete(:force)
  251. # lookups
  252. if data[:object]
  253. data[:object_lookup_id] = ObjectLookup.by_name(data[:object])
  254. end
  255. data.delete(:object)
  256. data[:name].downcase!
  257. # check new entry - is needed
  258. record = ObjectManager::Attribute.find_by(
  259. object_lookup_id: data[:object_lookup_id],
  260. name: data[:name],
  261. )
  262. if record
  263. # do not allow to overwrite certain attributes
  264. if !force
  265. data.delete(:editable)
  266. data.delete(:to_create)
  267. data.delete(:to_migrate)
  268. data.delete(:to_delete)
  269. data.delete(:to_config)
  270. end
  271. # if data_option has changed, store it for next migration
  272. if !force
  273. %i[name display data_type position active].each do |key|
  274. next if record[key] == data[key]
  275. record[:data_option_new] = data[:data_option] if data[:data_option] # bring the data options over as well, when there are changes to the fields above
  276. data[:to_config] = true
  277. break
  278. end
  279. if record[:data_option] != data[:data_option]
  280. # do we need a database migration?
  281. if record[:data_option][:maxlength] && data[:data_option][:maxlength] && record[:data_option][:maxlength].to_s != data[:data_option][:maxlength].to_s
  282. data[:to_migrate] = true
  283. end
  284. record[:data_option_new] = data[:data_option]
  285. data.delete(:data_option)
  286. data[:to_config] = true
  287. end
  288. end
  289. # update attributes
  290. data.each do |key, value|
  291. record[key.to_sym] = value
  292. end
  293. # check editable & name
  294. if !force
  295. record.check_editable
  296. record.check_name
  297. end
  298. record.save!
  299. return record
  300. end
  301. # do not allow to overwrite certain attributes
  302. if !force
  303. data[:editable] = true
  304. data[:to_create] = true
  305. data[:to_migrate] = true
  306. data[:to_delete] = false
  307. end
  308. record = ObjectManager::Attribute.new(data)
  309. # check editable & name
  310. if !force
  311. record.check_editable
  312. record.check_name
  313. end
  314. record.save!
  315. record
  316. end
  317. =begin
  318. remove attribute entry for an object
  319. ObjectManager::Attribute.remove(
  320. object: 'Ticket',
  321. name: 'group_id',
  322. )
  323. use "force: true" to delete also not editable fields
  324. =end
  325. def self.remove(data)
  326. # lookups
  327. if data[:object]
  328. data[:object_lookup_id] = ObjectLookup.by_name(data[:object])
  329. elsif data[:object_lookup_id]
  330. data[:object] = ObjectLookup.by_id(data[:object_lookup_id])
  331. else
  332. raise 'ERROR: need object or object_lookup_id param!'
  333. end
  334. data[:name].downcase!
  335. # check newest entry - is needed
  336. record = ObjectManager::Attribute.find_by(
  337. object_lookup_id: data[:object_lookup_id],
  338. name: data[:name],
  339. )
  340. if !record
  341. raise "ERROR: No such field #{data[:object]}.#{data[:name]}"
  342. end
  343. if !data[:force] && !record.editable
  344. raise "ERROR: #{data[:object]}.#{data[:name]} can't be removed!"
  345. end
  346. # check to make sure that no triggers, overviews, or schedulers references this attribute
  347. if ObjectManager::Attribute.attribute_used_by_references?(data[:object], data[:name])
  348. text = ObjectManager::Attribute.attribute_used_by_references_humaniced(data[:object], data[:name])
  349. raise "ERROR: #{data[:object]}.#{data[:name]} is referenced by #{text} and thus cannot be deleted!"
  350. end
  351. # if record is to create, just destroy it
  352. if record.to_create
  353. record.destroy
  354. return true
  355. end
  356. record.to_delete = true
  357. record.save
  358. end
  359. =begin
  360. get the attribute model based on object and name
  361. attribute = ObjectManager::Attribute.get(
  362. object: 'Ticket',
  363. name: 'group_id',
  364. )
  365. =end
  366. def self.get(data)
  367. # lookups
  368. if data[:object]
  369. data[:object_lookup_id] = ObjectLookup.by_name(data[:object])
  370. end
  371. data[:name].downcase!
  372. ObjectManager::Attribute.find_by(
  373. object_lookup_id: data[:object_lookup_id],
  374. name: data[:name],
  375. )
  376. end
  377. =begin
  378. get user based list of used object attributes
  379. attribute_list = ObjectManager::Attribute.by_object('Ticket', user)
  380. returns:
  381. [
  382. { name: 'api_key', display: 'API KEY', tag: 'input', null: true, edit: true, maxlength: 32 },
  383. { name: 'api_ip_regexp', display: 'API IP RegExp', tag: 'input', null: true, edit: true },
  384. { name: 'api_ip_max', display: 'API IP Max', tag: 'input', null: true, edit: true },
  385. ]
  386. =end
  387. def self.by_object(object, user)
  388. # lookups
  389. if object
  390. object_lookup_id = ObjectLookup.by_name(object)
  391. end
  392. # get attributes in right order
  393. result = ObjectManager::Attribute.where(
  394. object_lookup_id: object_lookup_id,
  395. active: true,
  396. to_create: false,
  397. to_delete: false,
  398. ).order('position ASC, name ASC')
  399. attributes = []
  400. result.each do |item|
  401. data = {
  402. name: item.name,
  403. display: item.display,
  404. tag: item.data_type,
  405. #:null => item.null,
  406. }
  407. if item.data_option[:permission]&.any?
  408. next if !user
  409. hint = false
  410. item.data_option[:permission].each do |permission|
  411. next if !user.permissions?(permission)
  412. hint = true
  413. break
  414. end
  415. next if !hint
  416. end
  417. if item.screens
  418. data[:screen] = {}
  419. item.screens.each do |screen, permission_options|
  420. data[:screen][screen] = {}
  421. permission_options.each do |permission, options|
  422. if permission == '-all-'
  423. data[:screen][screen] = options
  424. elsif user&.permissions?(permission)
  425. data[:screen][screen] = options
  426. end
  427. end
  428. end
  429. end
  430. if item.data_option
  431. data = data.merge(item.data_option.symbolize_keys)
  432. end
  433. attributes.push data
  434. end
  435. attributes
  436. end
  437. =begin
  438. get user based list of object attributes as hash
  439. attribute_list = ObjectManager::Attribute.by_object_as_hash('Ticket', user)
  440. returns:
  441. {
  442. 'api_key' => { name: 'api_key', display: 'API KEY', tag: 'input', null: true, edit: true, maxlength: 32 },
  443. 'api_ip_regexp' => { name: 'api_ip_regexp', display: 'API IP RegExp', tag: 'input', null: true, edit: true },
  444. 'api_ip_max' => { name: 'api_ip_max', display: 'API IP Max', tag: 'input', null: true, edit: true },
  445. }
  446. =end
  447. def self.by_object_as_hash(object, user)
  448. list = by_object(object, user)
  449. hash = {}
  450. list.each do |item|
  451. hash[ item[:name] ] = item
  452. end
  453. hash
  454. end
  455. =begin
  456. discard migration changes
  457. ObjectManager::Attribute.discard_changes
  458. returns
  459. true|false
  460. =end
  461. def self.discard_changes
  462. ObjectManager::Attribute.where('to_create = ?', true).each(&:destroy)
  463. ObjectManager::Attribute.where('to_delete = ? OR to_config = ?', true, true).each do |attribute|
  464. attribute.to_migrate = false
  465. attribute.to_delete = false
  466. attribute.to_config = false
  467. attribute.data_option_new = {}
  468. attribute.save
  469. end
  470. true
  471. end
  472. =begin
  473. check if we have pending migrations of attributes
  474. ObjectManager::Attribute.pending_migration?
  475. returns
  476. true|false
  477. =end
  478. def self.pending_migration?
  479. return false if migrations.blank?
  480. true
  481. end
  482. =begin
  483. get list of pending attributes migrations
  484. ObjectManager::Attribute.migrations
  485. returns
  486. [record1, record2, ...]
  487. =end
  488. def self.migrations
  489. ObjectManager::Attribute.where('to_create = ? OR to_migrate = ? OR to_delete = ? OR to_config = ?', true, true, true, true)
  490. end
  491. =begin
  492. start migration of pending attribute migrations
  493. ObjectManager::Attribute.migration_execute
  494. returns
  495. [record1, record2, ...]
  496. to send no browser reload event, pass false
  497. ObjectManager::Attribute.migration_execute(false)
  498. =end
  499. def self.migration_execute(send_event = true)
  500. # check if field already exists
  501. execute_db_count = 0
  502. execute_config_count = 0
  503. migrations.each do |attribute|
  504. model = attribute.object_lookup.name.constantize
  505. # remove field
  506. if attribute.to_delete
  507. if model.column_names.include?(attribute.name)
  508. ActiveRecord::Migration.remove_column model.table_name, attribute.name
  509. reset_database_info(model)
  510. end
  511. execute_db_count += 1
  512. attribute.destroy
  513. next
  514. end
  515. # config changes
  516. if attribute.to_config
  517. execute_config_count += 1
  518. if attribute.data_type == 'select' && attribute.data_option[:options]
  519. historical_options = attribute.data_option[:historical_options] || {}
  520. historical_options.update(attribute.data_option[:options])
  521. historical_options.update(attribute.data_option_new[:options])
  522. attribute.data_option_new[:historical_options] = historical_options
  523. end
  524. attribute.data_option = attribute.data_option_new
  525. attribute.data_option_new = {}
  526. attribute.to_config = false
  527. attribute.save!
  528. next if !attribute.to_create && !attribute.to_migrate && !attribute.to_delete
  529. end
  530. if attribute.data_type == 'select' && attribute.data_option[:options]
  531. attribute.data_option[:historical_options] = attribute.data_option[:options]
  532. end
  533. data_type = nil
  534. if attribute.data_type.match?(/^input|select|tree_select|richtext|textarea|checkbox$/)
  535. data_type = :string
  536. elsif attribute.data_type.match?(/^integer|user_autocompletion$/)
  537. data_type = :integer
  538. elsif attribute.data_type.match?(/^boolean|active$/)
  539. data_type = :boolean
  540. elsif attribute.data_type.match?(/^datetime$/)
  541. data_type = :datetime
  542. elsif attribute.data_type.match?(/^date$/)
  543. data_type = :date
  544. end
  545. # change field
  546. if model.column_names.include?(attribute.name)
  547. if attribute.data_type.match?(/^input|select|tree_select|richtext|textarea|checkbox$/)
  548. ActiveRecord::Migration.change_column(
  549. model.table_name,
  550. attribute.name,
  551. data_type,
  552. limit: attribute.data_option[:maxlength],
  553. null: true
  554. )
  555. elsif attribute.data_type.match?(/^integer|user_autocompletion|datetime|date$/)
  556. ActiveRecord::Migration.change_column(
  557. model.table_name,
  558. attribute.name,
  559. data_type,
  560. default: attribute.data_option[:default],
  561. null: true
  562. )
  563. elsif attribute.data_type.match?(/^boolean|active$/)
  564. ActiveRecord::Migration.change_column(
  565. model.table_name,
  566. attribute.name,
  567. data_type,
  568. default: attribute.data_option[:default],
  569. null: true
  570. )
  571. else
  572. raise "Unknown attribute.data_type '#{attribute.data_type}', can't update attribute"
  573. end
  574. # restart processes
  575. attribute.to_create = false
  576. attribute.to_migrate = false
  577. attribute.to_delete = false
  578. attribute.save!
  579. reset_database_info(model)
  580. execute_db_count += 1
  581. next
  582. end
  583. # create field
  584. if attribute.data_type.match?(/^input|select|tree_select|richtext|textarea|checkbox$/)
  585. ActiveRecord::Migration.add_column(
  586. model.table_name,
  587. attribute.name,
  588. data_type,
  589. limit: attribute.data_option[:maxlength],
  590. null: true
  591. )
  592. elsif attribute.data_type.match?(/^integer|user_autocompletion$/)
  593. ActiveRecord::Migration.add_column(
  594. model.table_name,
  595. attribute.name,
  596. data_type,
  597. default: attribute.data_option[:default],
  598. null: true
  599. )
  600. elsif attribute.data_type.match?(/^boolean|active$/)
  601. ActiveRecord::Migration.add_column(
  602. model.table_name,
  603. attribute.name,
  604. data_type,
  605. default: attribute.data_option[:default],
  606. null: true
  607. )
  608. elsif attribute.data_type.match?(/^datetime|date$/)
  609. ActiveRecord::Migration.add_column(
  610. model.table_name,
  611. attribute.name,
  612. data_type,
  613. default: attribute.data_option[:default],
  614. null: true
  615. )
  616. else
  617. raise "Unknown attribute.data_type '#{attribute.data_type}', can't create attribute"
  618. end
  619. # restart processes
  620. attribute.to_create = false
  621. attribute.to_migrate = false
  622. attribute.to_delete = false
  623. attribute.save!
  624. reset_database_info(model)
  625. execute_db_count += 1
  626. end
  627. # sent maintenance message to clients
  628. if send_event
  629. if execute_db_count.nonzero?
  630. if ENV['APP_RESTART_CMD']
  631. AppVersion.set(true, 'restart_auto')
  632. sleep 4
  633. AppVersionRestartJob.perform_later(ENV['APP_RESTART_CMD'])
  634. else
  635. AppVersion.set(true, 'restart_manual')
  636. end
  637. elsif execute_config_count.nonzero?
  638. AppVersion.set(true, 'config_changed')
  639. end
  640. end
  641. true
  642. end
  643. =begin
  644. where attributes are used by triggers, overviews or schedulers
  645. result = ObjectManager::Attribute.attribute_to_references_hash
  646. result = {
  647. ticket.category: {
  648. Trigger: ['abc', 'xyz'],
  649. Overview: ['abc1', 'abc2'],
  650. },
  651. ticket.field_b: {
  652. Trigger: ['abc'],
  653. Overview: ['abc1', 'abc2'],
  654. },
  655. },
  656. =end
  657. def self.attribute_to_references_hash
  658. objects = Trigger.select(:name, :condition) + Overview.select(:name, :condition) + Job.select(:name, :condition)
  659. attribute_list = {}
  660. objects.each do |item|
  661. item.condition.each do |condition_key, _condition_attributes|
  662. attribute_list[condition_key] ||= {}
  663. attribute_list[condition_key][item.class.name] ||= []
  664. next if attribute_list[condition_key][item.class.name].include?(item.name)
  665. attribute_list[condition_key][item.class.name].push item.name
  666. end
  667. end
  668. attribute_list
  669. end
  670. =begin
  671. is certain attribute used by triggers, overviews or schedulers
  672. ObjectManager::Attribute.attribute_used_by_references?('Ticket', 'attribute_name')
  673. =end
  674. def self.attribute_used_by_references?(object_name, attribute_name, references = attribute_to_references_hash)
  675. references.each do |reference_key, _relations|
  676. local_object, local_attribute = reference_key.split('.')
  677. next if local_object != object_name.downcase
  678. next if local_attribute != attribute_name
  679. return true
  680. end
  681. false
  682. end
  683. =begin
  684. is certain attribute used by triggers, overviews or schedulers
  685. result = ObjectManager::Attribute.attribute_used_by_references('Ticket', 'attribute_name')
  686. result = {
  687. Trigger: ['abc', 'xyz'],
  688. Overview: ['abc1', 'abc2'],
  689. }
  690. =end
  691. def self.attribute_used_by_references(object_name, attribute_name, references = attribute_to_references_hash)
  692. result = {}
  693. references.each do |reference_key, relations|
  694. local_object, local_attribute = reference_key.split('.')
  695. next if local_object != object_name.downcase
  696. next if local_attribute != attribute_name
  697. relations.each do |relation, relation_names|
  698. result[relation] ||= []
  699. result[relation].push relation_names.sort
  700. end
  701. break
  702. end
  703. result
  704. end
  705. =begin
  706. is certain attribute used by triggers, overviews or schedulers
  707. text = ObjectManager::Attribute.attribute_used_by_references_humaniced('Ticket', 'attribute_name', references)
  708. =end
  709. def self.attribute_used_by_references_humaniced(object_name, attribute_name, references = nil)
  710. result = if references.present?
  711. ObjectManager::Attribute.attribute_used_by_references(object_name, attribute_name, references)
  712. else
  713. ObjectManager::Attribute.attribute_used_by_references(object_name, attribute_name)
  714. end
  715. not_deletable_reason = ''
  716. result.each do |relation, relation_names|
  717. if not_deletable_reason.present?
  718. not_deletable_reason += '; '
  719. end
  720. not_deletable_reason += "#{relation}: #{relation_names.sort.join(',')}"
  721. end
  722. not_deletable_reason
  723. end
  724. def self.reset_database_info(model)
  725. model.connection.schema_cache.clear!
  726. model.reset_column_information
  727. # rebuild columns cache to reduce the risk of
  728. # race conditions in re-setting it with outdated data
  729. model.columns
  730. end
  731. def check_name
  732. return if !name
  733. raise 'Name can\'t get used, *_id and *_ids are not allowed' if name.match?(/.+?_(id|ids)$/i)
  734. raise 'Spaces in name are not allowed' if name.match?(/\s/)
  735. raise 'Only letters from a-z, numbers from 0-9, and _ are allowed' if !name.match?(/^[a-z0-9_]+$/)
  736. raise 'At least one letters is needed' if !name.match?(/[a-z]/)
  737. # do not allow model method names as attributes
  738. reserved_words = %w[destroy true false integer select drop create alter index table varchar blob date datetime timestamp url icon initials avatar permission validate subscribe unsubscribe translate search _type _doc _id id]
  739. raise "#{name} is a reserved word, please choose a different one" if name.match?(/^(#{reserved_words.join('|')})$/)
  740. # fixes issue #2236 - Naming an attribute "attribute" causes ActiveRecord failure
  741. begin
  742. ObjectLookup.by_id(object_lookup_id).constantize.instance_method_already_implemented? name
  743. rescue ActiveRecord::DangerousAttributeError
  744. raise "#{name} is a reserved word, please choose a different one"
  745. end
  746. record = object_lookup.name.constantize.new
  747. return true if !record.respond_to?(name.to_sym)
  748. raise "#{name} already exists!" if record.attributes.key?(name) && new_record?
  749. return true if record.attributes.key?(name)
  750. raise "#{name} is a reserved word, please choose a different one"
  751. end
  752. def check_editable
  753. return if editable
  754. raise 'Attribute not editable!'
  755. end
  756. private
  757. # when setting default values for boolean fields,
  758. # favor #nil? tests over ||= (which will overwrite `false`)
  759. def set_base_options
  760. local_data_option[:null] = true if local_data_option[:null].nil?
  761. case data_type
  762. when /^((tree_)?select|checkbox)$/
  763. local_data_option[:nulloption] = true if local_data_option[:nulloption].nil?
  764. local_data_option[:maxlength] ||= 255
  765. end
  766. end
  767. def data_option_must_have_appropriate_values
  768. data_option_validations
  769. .select { |validation| validation[:failed] }
  770. .each { |validation| errors.add(local_data_attr, validation[:message]) }
  771. end
  772. def data_type_must_not_change
  773. allowable_changes = %w[tree_select select input checkbox]
  774. return if !data_type_changed?
  775. return if (data_type_change - allowable_changes).empty?
  776. errors.add(:data_type, "can't be altered after creation " \
  777. '(delete the attribute and create another with the desired value)')
  778. end
  779. def local_data_option
  780. @local_data_option ||= send(local_data_attr)
  781. end
  782. def local_data_attr
  783. @local_data_attr ||= to_config ? :data_option_new : :data_option
  784. end
  785. def local_data_option=(val)
  786. send("#{local_data_attr}=", val)
  787. end
  788. def data_option_validations
  789. case data_type
  790. when 'input'
  791. [{ failed: %w[text password tel fax email url].exclude?(local_data_option[:type]),
  792. message: 'must have one of text/password/tel/fax/email/url for :type' },
  793. { failed: !local_data_option[:maxlength].to_s.match?(/^\d+$/),
  794. message: 'must have integer for :maxlength' }]
  795. when 'richtext'
  796. [{ failed: !local_data_option[:maxlength].to_s.match?(/^\d+$/),
  797. message: 'must have integer for :maxlength' }]
  798. when 'integer'
  799. [{ failed: !local_data_option[:min].to_s.match?(/^\d+$/),
  800. message: 'must have integer for :min' },
  801. { failed: !local_data_option[:max].to_s.match?(/^\d+$/),
  802. message: 'must have integer for :max' }]
  803. when /^((tree_)?select|checkbox)$/
  804. [{ failed: !local_data_option.key?(:default),
  805. message: 'must have value for :default' },
  806. { failed: local_data_option[:options].nil? && local_data_option[:relation].nil?,
  807. message: 'must have non-nil value for either :options or :relation' }]
  808. when 'boolean'
  809. [{ failed: !local_data_option.key?(:default),
  810. message: 'must have boolean/undefined value for :default' },
  811. { failed: local_data_option[:options].nil?,
  812. message: 'must have non-nil value for :options' }]
  813. when 'datetime'
  814. [{ failed: local_data_option[:future].nil?,
  815. message: 'must have boolean value for :future' },
  816. { failed: local_data_option[:past].nil?,
  817. message: 'must have boolean value for :past' },
  818. { failed: local_data_option[:diff].nil?,
  819. message: 'must have integer value for :diff (in hours)' }]
  820. when 'date'
  821. [{ failed: local_data_option[:diff].nil?,
  822. message: 'must have integer value for :diff (in days)' }]
  823. else
  824. []
  825. end
  826. end
  827. end