vario 1.0.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +68 -1
  3. data/Rakefile +0 -4
  4. data/app/assets/stylesheets/vario/application.css +316 -0
  5. data/app/assets/tailwind/vario/engine.css +6 -0
  6. data/app/controllers/vario/application_controller.rb +9 -2
  7. data/app/controllers/vario/topics_controller.rb +131 -0
  8. data/app/controllers/vario/values_controller.rb +27 -0
  9. data/app/javascript/vario/application.js +18 -0
  10. data/app/javascript/vario/controllers/refinements_controller.js +29 -0
  11. data/app/javascript/vario/controllers/search_controller.js +63 -0
  12. data/app/javascript/vario/controllers/sortable_controller.js +61 -0
  13. data/app/javascript/vario/controllers/tabs_controller.js +19 -0
  14. data/app/javascript/vario/controllers/topic_controller.js +40 -0
  15. data/app/models/vario/conditions.rb +158 -0
  16. data/app/models/vario/refinement.rb +38 -0
  17. data/app/models/vario/setting.rb +64 -3
  18. data/app/policies/vario/topic_policy.rb +37 -0
  19. data/app/views/vario/shared/_card.html.erb +25 -0
  20. data/app/views/vario/topics/_applies.html.erb +49 -0
  21. data/app/views/vario/topics/_nav.html.erb +28 -0
  22. data/app/views/vario/topics/_refinements.html.erb +41 -0
  23. data/app/views/vario/topics/_setting.html.erb +9 -0
  24. data/app/views/vario/topics/index.html.erb +3 -0
  25. data/app/views/vario/topics/show.html.erb +31 -0
  26. data/app/views/vario/values/_form.html.erb +20 -0
  27. data/config/importmap.rb +4 -0
  28. data/config/locales/en.yml +50 -0
  29. data/config/locales/nl.yml +50 -0
  30. data/config/routes.rb +11 -6
  31. data/db/migrate/20261118190000_add_value_to_vario_settings.rb +8 -0
  32. data/db/migrate/20261118190100_create_vario_refinements.rb +19 -0
  33. data/lib/generators/vario/topics_from_config/topics_from_config_generator.rb +189 -0
  34. data/lib/tasks/vario_tasks.rake +30 -0
  35. data/lib/vario/action_view_helpers.rb +119 -16
  36. data/lib/vario/active_record_helpers.rb +3 -2
  37. data/lib/vario/api.rb +49 -60
  38. data/lib/vario/backup.rb +50 -0
  39. data/lib/vario/card.rb +27 -0
  40. data/lib/vario/config.rb +36 -11
  41. data/lib/vario/context_variables.rb +69 -0
  42. data/lib/vario/converter.rb +113 -0
  43. data/lib/vario/engine.rb +27 -0
  44. data/lib/vario/migrator.rb +83 -0
  45. data/lib/vario/resolver.rb +71 -0
  46. data/lib/vario/settable.rb +41 -23
  47. data/lib/vario/settable_topic.rb +37 -0
  48. data/lib/vario/settings_reader.rb +45 -15
  49. data/lib/vario/topic.rb +299 -0
  50. data/lib/vario/topic_reader.rb +42 -0
  51. data/lib/vario/types.rb +64 -0
  52. data/lib/vario/version.rb +1 -1
  53. data/lib/vario.rb +16 -0
  54. metadata +116 -34
  55. data/app/controllers/vario/levels_controller.rb +0 -82
  56. data/app/controllers/vario/settings_controller.rb +0 -35
  57. data/app/views/vario/levels/_form.html.slim +0 -53
  58. data/app/views/vario/levels/create.js.erb +0 -4
  59. data/app/views/vario/levels/destroy.js.erb +0 -4
  60. data/app/views/vario/levels/update.js.erb +0 -4
  61. data/app/views/vario/settings/_levels.html.slim +0 -22
  62. data/app/views/vario/settings/_new_level.html.slim +0 -7
  63. data/app/views/vario/settings/_settings.html.slim +0 -24
  64. data/app/views/vario/settings/index.html.slim +0 -28
  65. data/app/views/vario/settings/levels.html.slim +0 -1
  66. data/app/views/vario/settings/show.html.slim +0 -13
@@ -0,0 +1,3 @@
1
+ <div class="vario-topics">
2
+ <p class="vario-topics__empty"><%= t('vario.pages.index.empty') %></p>
3
+ </div>
@@ -0,0 +1,31 @@
1
+ <div class="vario-topics<%= ' vario-topics--host' unless Vario.config.standalone? %>">
2
+ <%= render 'vario/topics/nav', topics: @topics, current: @topic if Vario.config.standalone? %>
3
+
4
+ <main class="vario-topic">
5
+ <%= form_with url: topic_path(@topic.key), method: :patch, builder: FormComponents::FormBuilder,
6
+ data: { controller: 'vario--topic', action: 'input->vario--topic#changed change->vario--topic#changed', 'vario--topic-confirm-value': t('vario.pages.show.leave') } do |form| %>
7
+ <header class="vario-topic__head">
8
+ <% if @topic.topic.icon %><i class="<%= @topic.topic.icon %> fa-fw vario-topic__icon" aria-hidden="true"></i><% end %>
9
+ <div class="vario-topic__title">
10
+ <h1><%= @topic.title %></h1>
11
+ <% if @topic.topic.description %><p><%= @topic.topic.description %></p><% end %>
12
+ </div>
13
+ <div class="vario-topic__savebar" data-vario--topic-target="savebar">
14
+ <span class="vario-topic__unsaved" hidden data-vario--topic-target="unsaved"><%= t('vario.pages.show.unsaved') %></span>
15
+ <%= link_to t('vario.pages.show.cancel'), topic_path(@topic.key), class: 'vario-button', hidden: true, data: { 'vario--topic-target': 'cancel', action: 'vario--topic#discard' } %>
16
+ <%= form.submit t('vario.pages.show.save'), class: 'vario-button vario-button--primary' %>
17
+ </div>
18
+ </header>
19
+
20
+ <div class="vario-topic__settings">
21
+ <% @topic.topic.definitions.each_value do |definition| %>
22
+ <%= render 'vario/topics/setting', form: form, definition: definition, setting: @settings[definition.key], settable: @settable, topic: @topic %>
23
+ <% end %>
24
+ </div>
25
+ <% end %>
26
+
27
+ <% if @topic.topic.context.any? %>
28
+ <%= render 'vario/topics/applies', topic: @topic, settable: @settable, applies: @applies %>
29
+ <% end %>
30
+ </main>
31
+ </div>
@@ -0,0 +1,20 @@
1
+ <%# Settings on a page of the host's (render_vario_settings): the values on exactly its context, or its own %>
2
+ <%= vario_card :vario_settings, title: t('vario.pages.values.title'), icon: 'fal fa-sliders' do %>
3
+ <%= form_with url: vario.values_path, method: :patch, builder: FormComponents::FormBuilder, class: 'vario-values' do |form| %>
4
+ <%= hidden_field_tag :settable, settable.to_sgid(for: 'Vario').to_s, id: nil %>
5
+ <%= hidden_field_tag :context, Vario.verifier.generate(context), id: nil %>
6
+ <% definitions.each do |definition| %>
7
+ <% setting = settable.vario_settings_by_name[definition.name] %>
8
+ <% object = context.empty? ? setting : setting&.refinement_on(context) %>
9
+ <% object ||= context.empty? ? Vario::Setting.new(name: definition.name, settable: settable) : Vario::Refinement.new %>
10
+ <%= fields_for "values[#{definition.name}]", object, builder: FormComponents::FormBuilder do |f| %>
11
+ <%= f.fieldset definition.label, description: definition.description, legend_position: :beside, id: "vario_value_#{definition.name.parameterize(separator: '_')}" do %>
12
+ <%= vario_value_field(f, definition, settable) %>
13
+ <% end %>
14
+ <% end %>
15
+ <% end %>
16
+ <div class="vario-values__actions">
17
+ <%= form.submit t('vario.pages.show.save'), class: 'vario-button vario-button--primary' %>
18
+ </div>
19
+ <% end %>
20
+ <% end %>
@@ -0,0 +1,4 @@
1
+ # Pins for the vario gem. The host app imports it with: import "vario"
2
+
3
+ pin "vario", to: "vario/application.js"
4
+ pin_all_from Vario::Engine.root.join("app/javascript/vario"), under: "vario", to: "vario"
@@ -1,5 +1,55 @@
1
1
  en:
2
2
  vario:
3
+ values:
4
+ "on": "On"
5
+ "off": "Off"
6
+ pages:
7
+ nav:
8
+ label: Settings
9
+ search: Search settings
10
+ none: No settings found.
11
+ index:
12
+ empty: There are no settings to show.
13
+ show:
14
+ unsaved: Unsaved changes
15
+ cancel: Cancel
16
+ leave: Leave this page? Your changes aren't saved.
17
+ save: Save
18
+ setting:
19
+ default: "Default: %{value}"
20
+ use_default: Default
21
+ applies:
22
+ title: What applies?
23
+ intro: Choose what to look at, and see which value every setting gets, and why.
24
+ show: Show
25
+ setting: Setting
26
+ value: Value
27
+ why: Why
28
+ nothing: Nothing
29
+ refinement: "Refinement %{priority} (%{summary})"
30
+ value_source: Its own value
31
+ default: The default
32
+ refinement:
33
+ all: and
34
+ any: or
35
+ always: Always
36
+ no_value: no value
37
+ refinements:
38
+ title: Refinements
39
+ hint: the first that applies wins
40
+ add: Add refinement
41
+ new: New refinement
42
+ drag: Drag to change its priority
43
+ enabled: Enabled
44
+ remove: Remove this refinement
45
+ then: then
46
+ value: Value
47
+ note: Note
48
+ values:
49
+ title: Settings
50
+ update:
51
+ saved: The settings have been saved.
52
+ not_saved: The settings couldn't be saved.
3
53
  levels:
4
54
  form:
5
55
  save: Save
@@ -1,5 +1,55 @@
1
1
  nl:
2
2
  vario:
3
+ values:
4
+ "on": Aan
5
+ "off": Uit
6
+ pages:
7
+ nav:
8
+ label: Instellingen
9
+ search: Zoek instellingen
10
+ none: Geen instellingen gevonden.
11
+ index:
12
+ empty: Er zijn geen instellingen om te tonen.
13
+ show:
14
+ unsaved: Niet-opgeslagen wijzigingen
15
+ cancel: Annuleren
16
+ leave: Deze pagina verlaten? Je wijzigingen zijn niet opgeslagen.
17
+ save: Opslaan
18
+ setting:
19
+ default: "Standaard: %{value}"
20
+ use_default: Standaard
21
+ applies:
22
+ title: Wat geldt?
23
+ intro: Kies waar je naar wilt kijken, en zie welke waarde elke instelling krijgt, en waarom.
24
+ show: Toon
25
+ setting: Instelling
26
+ value: Waarde
27
+ why: Waarom
28
+ nothing: Niets
29
+ refinement: "Verfijning %{priority} (%{summary})"
30
+ value_source: Eigen waarde
31
+ default: Standaard
32
+ refinement:
33
+ all: en
34
+ any: of
35
+ always: Altijd
36
+ no_value: geen waarde
37
+ refinements:
38
+ title: Verfijningen
39
+ hint: de eerste die van toepassing is, geldt
40
+ add: Verfijning toevoegen
41
+ new: Nieuwe verfijning
42
+ drag: Sleep om de prioriteit te wijzigen
43
+ enabled: Actief
44
+ remove: Verwijder deze verfijning
45
+ then: dan
46
+ value: Waarde
47
+ note: Notitie
48
+ values:
49
+ title: Instellingen
50
+ update:
51
+ saved: De instellingen zijn opgeslagen.
52
+ not_saved: De instellingen konden niet worden opgeslagen.
3
53
  levels:
4
54
  form:
5
55
  save: Opslaan
data/config/routes.rb CHANGED
@@ -1,10 +1,15 @@
1
1
  Vario::Engine.routes.draw do
2
- resources :settings do
3
- get :levels, on: :member
4
- resources :levels do
5
- member do
6
- patch :move
7
- end
2
+ # A settable's topics, the settable signed in its settable param
3
+ # (settable.to_sgid(for: 'Vario'))
4
+ resources :topics, only: %i[index show update], param: :key do
5
+ # For a setting's refinements' conditions: its variables at a path, and
6
+ # an object variable's records
7
+ member do
8
+ get :variables
9
+ get :records
8
10
  end
9
11
  end
12
+
13
+ # Settings on a page of the host's (render_vario_settings)
14
+ resource :values, only: :update
10
15
  end
@@ -0,0 +1,8 @@
1
+ class AddValueToVarioSettings < ActiveRecord::Migration[7.1]
2
+ def change
3
+ # The settable's own value for the setting, null when it has none
4
+ add_column :vario_settings, :value, :jsonb
5
+
6
+ add_index :vario_settings, %i[settable_type settable_id name], unique: true
7
+ end
8
+ end
@@ -0,0 +1,19 @@
1
+ class CreateVarioRefinements < ActiveRecord::Migration[7.1]
2
+ def change
3
+ # A setting's more specific values: the first enabled one whose conditions
4
+ # are met applies, by position
5
+ create_table :vario_refinements, id: :uuid do |t|
6
+ t.references :setting, type: :uuid, null: false, index: false, foreign_key: { to_table: :vario_settings, on_delete: :cascade }
7
+
8
+ t.integer :position, null: false
9
+ t.boolean :enabled, null: false, default: true
10
+ t.text :note
11
+ t.jsonb :conditions, null: false, default: { match: 'all', rules: [] }
12
+ t.jsonb :value
13
+
14
+ t.timestamps
15
+ end
16
+
17
+ add_index :vario_refinements, %i[setting_id position], unique: true
18
+ end
19
+ end
@@ -0,0 +1,189 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/generators'
4
+
5
+ module Vario
6
+ module Generators
7
+ # Topics (app/settings/) and their texts (config/locales/) from the 1.x
8
+ # settings in the app's config (config/initializers/vario.rb), to trim:
9
+ #
10
+ # bin/rails g vario:topics_from_config [--locale=en]
11
+ #
12
+ # A topic per group, its context the keys its settings use (location_id
13
+ # is location, a drop or the model; other keys plain values); choices
14
+ # from a collection, or from a collection_proc that only builds a list
15
+ # (those that look at the setting or Current are left as a TODO).
16
+ class TopicsFromConfigGenerator < Rails::Generators::Base
17
+ class_option :locale, type: :string, default: 'en', desc: 'The locale of the 1.x descriptions'
18
+
19
+ def create_topics
20
+ topics.each do |topic|
21
+ create_file "app/settings/#{topic[:class_name].underscore}.rb", topic_source(topic)
22
+ end
23
+ end
24
+
25
+ def create_locale
26
+ texts = topics.each_with_object({}) do |topic, hash|
27
+ hash[topic[:key]] ||= { 'title' => topic[:key].humanize, 'settings' => {} }
28
+ topic[:settings].each do |setting|
29
+ hash[topic[:key]]['settings'][setting[:key]] = { 'label' => setting[:key].humanize, 'description' => setting[:description] }.compact
30
+ end
31
+ end
32
+
33
+ create_file "config/locales/vario.#{options[:locale]}.yml", { options[:locale] => { 'vario' => { 'topics' => texts } } }.to_yaml(line_width: -1)
34
+ end
35
+
36
+ def show_notes
37
+ notes = []
38
+ value_proc_keys = topics.flat_map { |topic| topic[:keys] }.uniq.select { |key| Vario.config.key_data_for(key)[:value_proc] }
39
+ value_proc_keys.each do |key|
40
+ notes << "#{key} had a value_proc: add config.context_default :#{key.to_s.delete_suffix('_id')}, -> { ... }"
41
+ end
42
+ Vario.config.instance_variable_get(:@show_group_if).each_key do |group|
43
+ notes << "#{group} had show_group_if: add a #{group.camelize}SettingsPolicy < Vario::TopicPolicy (show?)"
44
+ end
45
+ notes << 'TODOs left in the topics: choices that need the settable (choices: ->(settable) { ... }) or are records (setting :x, ShippingMethod)' if topics.any? { |topic| topic[:settings].any? { |setting| setting[:todo] } }
46
+
47
+ notes.each { |note| say_status :note, note, :yellow }
48
+ end
49
+
50
+ private
51
+
52
+ def topics
53
+ @topics ||= begin
54
+ class_names = []
55
+ Vario.config.settable_settings.flat_map do |settable_type, settings|
56
+ settings.group_by { |name, _options| name.include?('.') ? name.split('.', 2).first : 'general' }.map do |group, group_settings|
57
+ class_name = "#{group.camelize}Settings"
58
+ class_name = "#{settable_type}#{class_name}" if class_names.include?(class_name)
59
+ class_names << class_name
60
+
61
+ build_topic(settable_type, group, class_name, group_settings)
62
+ end
63
+ end
64
+ end
65
+ end
66
+
67
+ def build_topic(settable_type, group, class_name, group_settings)
68
+ settings = group_settings.map { |name, options| build_setting(group, name, options) }
69
+ keys = settings.flat_map { |setting| setting[:keys] }.uniq
70
+
71
+ settings.each do |setting|
72
+ setting[:context] = setting[:keys].map { |key| root_for(key) } unless setting[:keys] == keys
73
+ end
74
+
75
+ { settable_type: settable_type, key: group, class_name: class_name, custom_key: class_name != "#{group.camelize}Settings",
76
+ keys: keys, context: keys.to_h { |key| [root_for(key), root_type_for(key)] }, settings: settings }
77
+ end
78
+
79
+ def build_setting(group, name, options)
80
+ key = name.include?('.') ? name.split('.', 2).last : name
81
+ type = type_for(options)
82
+ choices, todo = choices_for(options, type)
83
+
84
+ { key: key, name: (name unless name.include?('.')), type: type, default: default_for(options, type),
85
+ choices: choices, todo: todo, keys: Array(options[:keys]).map(&:to_sym), description: description_for(options) }
86
+ end
87
+
88
+ # Not the one 1.x makes up without one
89
+ def description_for(options)
90
+ options[:description] unless options[:description].to_s.start_with?('Configuration for ')
91
+ end
92
+
93
+ def type_for(options)
94
+ case options[:type]
95
+ when :symbol, :select then :string
96
+ when :string then options[:default].to_s.match?(/\A\d{1,2}:\d{2}\z/) ? :time : :string
97
+ else options[:type]
98
+ end
99
+ end
100
+
101
+ def default_for(options, type)
102
+ default = options[:default]
103
+ return if default.nil? || (default.respond_to?(:empty?) && default.empty?)
104
+
105
+ default = default.map(&:to_s) if type == :array
106
+ default.is_a?(Symbol) ? default.to_s : default
107
+ end
108
+
109
+ # [source, todo]
110
+ def choices_for(options, type)
111
+ if options[:collection]
112
+ [options[:collection].map { |label, value| [label.to_s, value.to_s] }.inspect, nil]
113
+ elsif options[:collection_proc]
114
+ source = proc_source(options[:collection_proc])
115
+ return [nil, "choices, from 1.x's collection_proc: #{proc_location(options[:collection_proc])}"] unless source
116
+ return [nil, "choices, from 1.x's collection_proc: #{source}"] if source.match?(/@setting|account_for|Current\./)
117
+
118
+ # Records by id: a record picker
119
+ model = source[/\A->\s*\{\s*([A-Z]\w*(?:::[A-Z]\w*)*)\./, 1]
120
+ return [source, "#{model} records? setting :x, #{model}"] if model && source.match?(/\.id\]/)
121
+
122
+ [source, nil]
123
+ end
124
+ end
125
+
126
+ # The lambda's source, when it's on its line as "collection_proc: -> { ... }"
127
+ def proc_source(block)
128
+ file, line = block.source_location
129
+ return unless file && File.exist?(file)
130
+
131
+ text = File.readlines(file)[line - 1].to_s
132
+ start = text.index('collection_proc:')
133
+ return unless start
134
+
135
+ text = text[(start + 'collection_proc:'.length)..].lstrip
136
+ return unless text.start_with?('->')
137
+
138
+ depth = 0
139
+ text.each_char.with_index do |char, index|
140
+ depth += 1 if char == '{'
141
+ depth -= 1 if char == '}'
142
+ return text[0..index] if char == '}' && depth.zero?
143
+ end
144
+ nil
145
+ end
146
+
147
+ def proc_location(block)
148
+ block.source_location&.join(':')
149
+ end
150
+
151
+ # location for location_id, when there is a drop or a model for it;
152
+ # else the key
153
+ def root_for(key)
154
+ model_root_type(key) ? key.to_s.delete_suffix('_id') : key.to_s
155
+ end
156
+
157
+ def root_type_for(key)
158
+ model_root_type(key) || (Vario.config.key_data_for(key)[:type] == :boolean ? ':boolean' : ':string')
159
+ end
160
+
161
+ def model_root_type(key)
162
+ return unless key.to_s.end_with?('_id')
163
+
164
+ name = key.to_s.delete_suffix('_id').camelize
165
+ return "#{name}Drop" if "#{name}Drop".safe_constantize
166
+ name if name.safe_constantize.is_a?(Class)
167
+ end
168
+
169
+ def topic_source(topic)
170
+ lines = ['# frozen_string_literal: true', '', "class #{topic[:class_name]} < Vario::Topic", " settable #{topic[:settable_type]}"]
171
+ lines << " key '#{topic[:key]}'" if topic[:custom_key]
172
+ lines << " context #{topic[:context].map { |root, type| "#{root}: #{type}" }.join(', ')}" if topic[:context].any?
173
+ lines << ''
174
+
175
+ topic[:settings].each do |setting|
176
+ lines << " # TODO: #{setting[:todo]}" if setting[:todo]
177
+ arguments = [":#{setting[:key]}", ":#{setting[:type]}"]
178
+ arguments << "default: #{setting[:default].inspect}" unless setting[:default].nil?
179
+ arguments << "choices: #{setting[:choices]}" if setting[:choices]
180
+ arguments << "context: %i[#{setting[:context].join(' ')}]" if setting[:context]
181
+ arguments << "name: '#{setting[:name]}'" if setting[:name]
182
+ lines << " setting #{arguments.join(', ')}"
183
+ end
184
+
185
+ (lines << 'end').join("\n") + "\n"
186
+ end
187
+ end
188
+ end
189
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ namespace :vario do
4
+ desc "Convert 1.x settings (levels) to values and refinements; FORCE=1 also those already converted"
5
+ task migrate: :environment do
6
+ puts Vario::Migrator.new(force: ENV['FORCE'].present?).call(apply: true)
7
+ end
8
+
9
+ desc 'Write all settings and refinements to a JSON file (FILE, else vario_backup_<time>.json), to restore before running vario:migrate again'
10
+ task backup: :environment do
11
+ path = ENV['FILE'].presence || "vario_backup_#{Time.current.strftime('%Y%m%d%H%M%S')}.json"
12
+ counts = Vario::Backup.write(path)
13
+ puts "Backed up #{counts['settings']} settings and #{counts['refinements']} refinements to #{path}"
14
+ end
15
+
16
+ desc 'Replace all settings and refinements by those of a backup (FILE), exactly as they were then'
17
+ task restore: :environment do
18
+ path = ENV['FILE'].presence or abort 'FILE=<backup> is required'
19
+ counts = Vario::Backup.restore(path)
20
+ puts "Replaced #{counts[:before]['settings']} settings and #{counts[:before]['refinements']} refinements " \
21
+ "by #{counts[:after]['settings']} and #{counts[:after]['refinements']} from #{path}"
22
+ end
23
+
24
+ namespace :migrate do
25
+ desc 'What vario:migrate would do, per settable, without changing anything'
26
+ task report: :environment do
27
+ puts Vario::Migrator.new(force: ENV['FORCE'].present?).call(apply: false)
28
+ end
29
+ end
30
+ end
@@ -2,30 +2,133 @@
2
2
 
3
3
  module Vario
4
4
  module ActionViewHelpers
5
- def render_vario_settings(*args)
6
- settings_with_contexts = []
5
+ # The settings topics the user may see, as items of the host's menu
6
+ # (Menus::Builder's, with config.layout = :host): their settings'
7
+ # labels and descriptions as the link's keywords, for its search.
8
+ #
9
+ # m.group :settings do
10
+ # vario_menu_items(m)
11
+ # end
12
+ def vario_menu_items(menu, settable = Vario.config.current_settable)
13
+ return unless settable
14
+
15
+ SettableTopic.visible(settable, SettableTopic.user_of(controller)).each do |topic|
16
+ keywords = topic.topic.definitions.values.flat_map { |definition| [definition.label, definition.description] }.compact.join(' ')
17
+ menu.item :"vario_#{topic.key}", label: topic.title, icon: topic.topic.icon, link: vario.topic_path(topic.key),
18
+ link_attributes: { data: { keywords: keywords } }
19
+ end
20
+ end
7
21
 
22
+ # Settings on a page of the host's, as 1.x's: those of a settable, with
23
+ # a context, the values on exactly that (customer_id: 5, as the API's),
24
+ # else its own values. A form per settable, back to the page when saved.
25
+ #
26
+ # <%= render_vario_settings(Current.account, 'allocation.auto_allocate', 'shipping.partial_shipping', { customer_id: @customer.id }) %>
27
+ # <%= render_vario_settings([account, 'hide_couriers'], [account, 'print_node.api_key']) %>
28
+ def render_vario_settings(*args)
8
29
  args = [args] unless args.first.is_a?(Array)
9
- args.each do |argument_set|
10
- settable = argument_set.first
11
30
 
12
- if argument_set.last.is_a?(Hash)
13
- setting_names = argument_set[1..-2]
14
- context = argument_set.last
15
- else
16
- setting_names = argument_set[1..-1]
17
- context = {}
31
+ safe_join(args.map do |settable, *names|
32
+ context = names.last.is_a?(Hash) ? names.pop : {}
33
+ context = context.to_h { |key, value| [key.to_s, value.to_s] }
34
+ definitions = names.map do |name|
35
+ definition = Topic.definition(settable, name)
36
+ raise UnknownSetting, "Setting '#{name}' is not defined for #{settable.class.name}" unless definition
37
+
38
+ unknown = context.keys - definition.legacy_keys
39
+ raise ArgumentError, "Setting '#{name}' doesn't take #{unknown.join(', ')}" if unknown.any?
40
+
41
+ definition
18
42
  end
19
43
 
20
- Vario.config.pre_create_settings(settable)
21
- settable.settings.where(name: setting_names).each do |setting|
22
- settings_with_contexts << { setting: setting, context: context }
44
+ render 'vario/values/form', settable: settable, definitions: definitions, context: context
45
+ end)
46
+ end
47
+
48
+ # The control for a setting's own value, or a refinement's, by the
49
+ # setting's type (form's object is the Setting or the Refinement). Empty is
50
+ # nothing (the default applies), so a boolean is a select, not a switch.
51
+ def vario_value_field(form, definition, settable, label: definition.label, hint: true)
52
+ value = form.object.value
53
+ default = definition.human(definition.default_value, settable)
54
+ options = { label: label, hide_label: true }
55
+ options[:description] = t('vario.pages.setting.default', value: default) if hint && default.present?
56
+ choices = definition.choices_for(settable).map { |choice| choice.is_a?(Array) ? [choice.first, choice.last.to_s] : [choice.to_s, choice.to_s] }
57
+
58
+ case definition.type
59
+ when :boolean
60
+ form.select :value, [[t('vario.values.on'), 'true'], [t('vario.values.off'), 'false']], { include_blank: t('vario.pages.setting.use_default'), selected: value.nil? ? '' : value.to_s, **options }
61
+ when :integer then form.text_field :value, type: 'number', step: 1, **options
62
+ when :decimal then form.text_field :value, type: 'number', step: 'any', **options
63
+ when :time then form.text_field :value, type: 'time', **options
64
+ when :text then form.text_area :value, rows: 3, **options
65
+ when :hash then form.text_area :value, value: (definition.human(value) if value), rows: 4, **options
66
+ when :array
67
+ if choices.any?
68
+ form.collection_check_boxes :value, choices, :last, :first, { checked: Array(value).map(&:to_s), **options }
69
+ else
70
+ form.text_area :value, value: Array(value).join("\n"), rows: 3, **options
23
71
  end
72
+ else
73
+ choices = definition.records(settable).map { |record| [Topic.label_of(record), record.id.to_s] } if definition.model
74
+ if choices.any? || definition.model
75
+ form.select :value, choices, { include_blank: t('vario.pages.setting.use_default'), selected: value.to_s, **options }
76
+ else
77
+ form.text_field :value, **options
78
+ end
79
+ end
80
+ end
81
+
82
+ # A refinement in a line, for when it's closed: "Product is Apple and
83
+ # environment is test → 10"
84
+ def vario_refinement_summary(refinement, definition, settable, variables)
85
+ conditions = refinement.conditions.to_h.stringify_keys
86
+ rules = Array(conditions['rules']).map do |rule|
87
+ rule = rule.to_h.stringify_keys
88
+ label, type = variables.describe(rule['variable'])
89
+ value = case rule['operator']
90
+ when 'is_empty', 'isnt_empty' then nil
91
+ when 'between' then "#{rule['value']} – #{rule['value_to']}"
92
+ else type == 'object' ? vario_record_label(variables.model(rule['variable']), rule['value']) : rule['value']
93
+ end
94
+ [label, t("entdec.conditions.operators.#{rule['operator']}"), value].compact.join(' ')
95
+ end
96
+ match = conditions['match'] == 'any' ? 'any' : 'all'
97
+ text = rules.any? ? rules.join(" #{t("vario.pages.refinement.#{match}")} ") : t('vario.pages.refinement.always')
98
+ value = definition.human(refinement.value, settable)
99
+ "#{text} → #{value.presence || t('vario.pages.refinement.no_value')}"
100
+ end
101
+
102
+ def vario_record_label(model, id)
103
+ record = model&.find_by(model.primary_key => id) if id.present?
104
+ record ? Topic.label_of(record) : id
105
+ end
106
+
107
+ # The conditions editor for a refinement (EntDec::Conditions, records
108
+ # from the setting's context)
109
+ def vario_conditions(form, definition, settable, variables, variables_url:, records_url:)
110
+ conditions = form.object.conditions.to_h.stringify_keys
111
+ records = lambda do |path|
112
+ model = variables.model(path)
113
+ model ? Topic.records_of(model, settable).map { |record| [Topic.label_of(record), record.id] } : []
24
114
  end
25
115
 
26
- render partial: 'vario/settings/settings', locals: {
27
- settings_with_contexts: settings_with_contexts
28
- }
116
+ entdec_conditions(name: "#{form.object_name}[conditions]", match: conditions['match'], rules: Array(conditions['rules']),
117
+ variables_url: variables_url, describe: ->(path) { variables.describe(path) }, records_url: records_url, records: records)
118
+ end
119
+
120
+ # A card with a title and icon, and the actions and tabs its block adds
121
+ # (Vario::Card), else what the block gives
122
+ #
123
+ # <%= vario_card :vario_settings, title: 'Settings', icon: 'fad fa-sliders' do |card| %>
124
+ # <% card.tab :shipping do %>
125
+ # ...
126
+ # <% end %>
127
+ # <% end %>
128
+ def vario_card(name, title:, icon: nil, &block)
129
+ card = Vario::Card.new(self)
130
+ body = capture(card, &block)
131
+ render 'vario/shared/card', name: name.to_s.parameterize(separator: '_'), title: title, icon: icon, card: card, body: body
29
132
  end
30
133
  end
31
134
  end
@@ -11,11 +11,12 @@ module Vario
11
11
 
12
12
  class_methods do
13
13
  def settable(options = {})
14
- include Vario::Settable
15
-
16
14
  configuration = { name: :settings }
17
15
  configuration.update(options) if options.is_a?(Hash)
18
16
 
17
+ class_attribute :vario_settings_association, instance_writer: false, default: configuration[:name]
18
+ include Vario::Settable
19
+
19
20
  has_many configuration[:name], as: :settable, class_name: 'Vario::Setting'
20
21
  end
21
22
  end