20230801092655_issue_4543_organization_vip.rb 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Issue4543OrganizationVip < ActiveRecord::Migration[6.1]
  3. RESERVED_NAME = 'vip'.freeze
  4. SANITIZED_NAME = '_vip'.freeze
  5. VIP_ATTRIBUTE_PAYLOAD = {
  6. name: 'vip',
  7. display: 'VIP',
  8. data_type: 'boolean',
  9. data_option: {
  10. null: true,
  11. default: false,
  12. item_class: 'formGroup--halfSize',
  13. options: {
  14. false => 'no',
  15. true => 'yes',
  16. },
  17. translate: true,
  18. permission: ['admin.organization'],
  19. },
  20. editable: false,
  21. active: true,
  22. screens: {
  23. edit: {
  24. '-all-' => {
  25. null: true,
  26. },
  27. },
  28. create: {
  29. '-all-' => {
  30. null: true,
  31. },
  32. },
  33. view: {
  34. '-all-' => {
  35. shown: false,
  36. },
  37. },
  38. },
  39. position: 1450,
  40. }.freeze
  41. def change
  42. # return if it's a new setup
  43. return if !Setting.exists?(name: 'system_init_done')
  44. # If there is already a boolean 'vip' attribute, we reuse it,
  45. # but switch it to the new values.
  46. return if update_custom_vip_boolean_attribute
  47. # If there is a 'vip' attribute of another type, we rename it
  48. # to '_vip' and create the new internal attribute thereafter.
  49. rename_custom_vip_attribute
  50. create_vip_db_column
  51. create_vip_attribute
  52. end
  53. private
  54. def custom_vip_attribute
  55. ObjectManager::Attribute.get(object: 'Organization', name: RESERVED_NAME.dup)
  56. end
  57. def update_custom_vip_boolean_attribute
  58. return false if !custom_vip_attribute || custom_vip_attribute.data_type != 'boolean'
  59. custom_vip_attribute.update!(**VIP_ATTRIBUTE_PAYLOAD)
  60. true
  61. end
  62. def rename_custom_vip_attribute
  63. return if !custom_vip_attribute
  64. custom_vip_attribute.update!(name: SANITIZED_NAME)
  65. return if ActiveRecord::Base.connection.columns('organizations').map(&:name).exclude?(RESERVED_NAME)
  66. ActiveRecord::Migration.rename_column(:organizations, RESERVED_NAME.to_sym, SANITIZED_NAME.to_sym)
  67. Organization.connection.schema_cache.clear!
  68. Organization.reset_column_information
  69. end
  70. def create_vip_db_column
  71. change_table :organizations do |t|
  72. t.boolean :vip, default: false, null: false
  73. end
  74. Organization.reset_column_information
  75. end
  76. def create_vip_attribute
  77. UserInfo.current_user_id = 1
  78. ObjectManager::Attribute.add(
  79. **VIP_ATTRIBUTE_PAYLOAD,
  80. force: true,
  81. object: 'Organization',
  82. to_create: false,
  83. to_migrate: false,
  84. to_delete: false,
  85. )
  86. end
  87. end