qube_rails 0.2.1 → 0.3.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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +105 -0
  3. data/README.md +213 -56
  4. data/app/assets/javascripts/qube_rails/question.js +80 -41
  5. data/app/assets/stylesheets/qube_rails.css +143 -0
  6. data/app/controllers/qube_rails/connections_controller.rb +19 -3
  7. data/app/controllers/qube_rails/storyboard_controller.rb +1 -1
  8. data/app/models/qube_rails/connection.rb +110 -8
  9. data/app/models/qube_rails/quickbooks_record.rb +22 -0
  10. data/app/views/qube_rails/_manage_connection.html.erb +19 -0
  11. data/app/views/qube_rails/question/_choice.html.erb +2 -4
  12. data/app/views/qube_rails/question/_disclosure.html.erb +7 -0
  13. data/app/views/qube_rails/question/_footer.html.erb +2 -8
  14. data/app/views/qube_rails/question/_inline_search.html.erb +12 -0
  15. data/app/views/qube_rails/question/_pick.html.erb +25 -7
  16. data/app/views/qube_rails/question/_picks.html.erb +2 -3
  17. data/app/views/qube_rails/question/_question.html.erb +22 -13
  18. data/app/views/qube_rails/question/fields/_search.html.erb +3 -2
  19. data/app/views/qube_rails/storyboard/show.html.erb +4 -3
  20. data/config/locales/en.yml +7 -0
  21. data/config/routes.rb +2 -0
  22. data/db/migrate/20261124000000_add_qube_company_file_change.rb +17 -0
  23. data/lib/generators/qube_rails/templates/connection_events.rb.tt +17 -1
  24. data/lib/qube_rails/configuration.rb +2 -0
  25. data/lib/qube_rails/connection_events.rb +67 -7
  26. data/lib/qube_rails/engine.rb +1 -0
  27. data/lib/qube_rails/link_check.rb +274 -0
  28. data/lib/qube_rails/operation.rb +1 -0
  29. data/lib/qube_rails/question_view.rb +170 -118
  30. data/lib/qube_rails/request.rb +2 -0
  31. data/lib/qube_rails/storyboard/ask_about_add.json +1 -1
  32. data/lib/qube_rails/storyboard/choose.json +2 -2
  33. data/lib/qube_rails/storyboard/enum_select.json +1 -1
  34. data/lib/qube_rails/storyboard/missing_record.json +1 -1
  35. data/lib/qube_rails/storyboard/name_clash.json +41 -3
  36. data/lib/qube_rails/storyboard/near_match.json +8 -3
  37. data/lib/qube_rails/storyboard/number_boolean.json +1 -1
  38. data/lib/qube_rails/storyboard/record_search.json +2 -2
  39. data/lib/qube_rails/storyboard/refusal.json +7 -2
  40. data/lib/qube_rails/storyboard/rows.json +35 -18
  41. data/lib/qube_rails/storyboard.rb +21 -5
  42. data/lib/qube_rails/sync_status.rb +12 -1
  43. data/lib/qube_rails/version.rb +1 -1
  44. data/lib/qube_rails.rb +9 -0
  45. metadata +6 -1
@@ -0,0 +1,274 @@
1
+ # frozen_string_literal: true
2
+
3
+ module QubeRails
4
+ # Checks a connection's stale links (the old company file's, after
5
+ # connection.company_file_changed) against the file it opens now, once it's connected: a plain
6
+ # request per kind, querying up to BATCH of its ids (ListID or TxnID). An id found there with the
7
+ # same name is kept (current again, with the answer's EditSequence); one found under another name
8
+ # waits for the app's review (Connection#confirm_link / #reject_link); one not found is kept as
9
+ # missing. A kind that can't be looked up by id is kept as missing when the check starts. All are
10
+ # checked again on the next company file change. README, "A different company file".
11
+ #
12
+ # Its record is the connection, and its slug "qube_rails.check_links:<kind>", so it needs no
13
+ # entry in config.operations. The stale rows are its state: a check that's queued again (a second
14
+ # connected, a retried webhook) asks only about what is still stale.
15
+ class LinkCheck < Request
16
+ SLUG_PREFIX = "qube_rails.check_links:"
17
+ BATCH = 50
18
+ # How long after a check ended (or a queue got no answer) a held record queues it again.
19
+ RETRY_AFTER = 5 * 60
20
+
21
+ # Which id each kind's query takes, when the qube_sync gem's Operations::INDEX can't say (an
22
+ # older gem, or the inline backend). A kind in neither is never queried: it's kept as missing.
23
+ TXN_KINDS = %w[
24
+ ar_refund_credit_card bill bill_payment_check bill_payment_credit_card build_assembly charge check
25
+ credit_card_charge credit_card_credit credit_memo deposit estimate inventory_adjustment invoice
26
+ item_receipt journal_entry paycheck payroll_liability_adjustment payroll_liability_check
27
+ payroll_prior_payment payroll_year_to_date_adjustment purchase_order receive_payment sales_order
28
+ sales_receipt sales_tax_payment_check time_tracking transaction transfer transfer_inventory
29
+ vehicle_mileage vendor_credit
30
+ ].freeze
31
+ LIST_KINDS = %w[
32
+ account billing_rate class currency customer customer_msg customer_type date_driven_terms employee
33
+ entity inventory_site item item_discount item_fixed_asset item_group item_inventory
34
+ item_inventory_assembly item_non_inventory item_other_charge item_payment item_sales_tax
35
+ item_sales_tax_group item_service item_sites item_subtotal job_type lead other_name payment_method
36
+ payroll_item payroll_item_non_wage payroll_item_wage price_level sales_rep sales_tax_code
37
+ ship_method standard_terms terms to_do unit_of_measure_set vehicle vendor vendor_type
38
+ workers_comp_code
39
+ ].freeze
40
+
41
+ # "list_id" or "txn_id": what kind's query looks records up by, from the gem's INDEX when it
42
+ # says, else the lists above; nil for a kind that can't be looked up by id.
43
+ def self.id_param(kind)
44
+ entry = defined?(QubeSync::Operations::INDEX) ? QubeSync::Operations::INDEX["#{kind}.query"] : nil
45
+ return entry[:id_param] if entry&.key?(:id_param)
46
+ return "txn_id" if TXN_KINDS.include?(kind.to_s)
47
+
48
+ LIST_KINDS.include?(kind.to_s) ? "list_id" : nil
49
+ end
50
+
51
+ # Queues a check for each kind with stale links, when the connection is connected; a kind
52
+ # whose check is still going keeps it. A kind with no id to query is settled as missing at once.
53
+ # Returns the requests.
54
+ def self.start(connection)
55
+ return [] unless connection.connected? && !connection.qube_id.to_s.empty?
56
+
57
+ kinds = connection.stale_links.distinct.pluck(:kind).sort
58
+ unqueryable, queryable = kinds.partition { |kind| id_param(kind).nil? }
59
+ unqueryable.each { |kind| settle_unqueryable(connection, kind) }
60
+ queryable.filter_map do |kind|
61
+ self.for(kind).queue(connection, connection)
62
+ rescue Backend::APIError => e
63
+ raise unless e.status.between?(400, 499)
64
+
65
+ QubeRails.logger.warn("QuBe Sync: connection #{connection.id}: couldn't check its #{kind} links (#{e.status})")
66
+ nil
67
+ end
68
+ end
69
+
70
+ # From Connection#wait_for_link_check!, for a held record's stale kinds: queues a kind's check
71
+ # again when its last one ended (or its queue got no answer) more than RETRY_AFTER ago, or it
72
+ # has none. Errors are logged: the caller still raises LinkBeingChecked.
73
+ def self.revive(connection, kinds)
74
+ return unless connection.connected? && !connection.qube_id.to_s.empty?
75
+
76
+ kinds.each do |kind|
77
+ if id_param(kind).nil?
78
+ settle_unqueryable(connection, kind)
79
+ next
80
+ end
81
+ check = self.for(kind)
82
+ last = QubeRails::QueuedRequest.where(connection: connection).latest_for(connection, check::SLUG)
83
+ next unless last.nil? || dormant?(last)
84
+
85
+ last.touch if last && !last.ended? # the back-off counts from this try
86
+ check.queue(connection, connection)
87
+ rescue Backend::APIError, *Backend::NETWORK_ERRORS => e
88
+ QubeRails.logger.warn("QuBe Sync: connection #{connection.id}: couldn't queue its #{kind} link check " \
89
+ "again (#{e.class})")
90
+ end
91
+ end
92
+
93
+ def self.dormant?(row)
94
+ since = row.ended? ? row.ended_at : (row.qube_id.nil? ? row.updated_at : nil)
95
+ !since.nil? && since < Time.now - RETRY_AFTER
96
+ end
97
+ private_class_method :dormant?
98
+
99
+ # Links of a kind no query can look up: kept as missing, and reported like a checked batch.
100
+ def self.settle_unqueryable(connection, kind)
101
+ links = connection.transaction do
102
+ rows = connection.stale_links.where(kind: kind).lock.to_a
103
+ now = Time.now
104
+ rows.each { |link| link.update!(stale_since: nil, missing_since: now) }
105
+ end
106
+ return if links.empty?
107
+
108
+ report(connection, kind, relinked: [], review: [], missing: links)
109
+ end
110
+ private_class_method :settle_unqueryable
111
+
112
+ def self.report(connection, kind, result)
113
+ found = result[:relinked].size + result[:review].size
114
+ QubeRails.logger.info("QuBe Sync: connection #{connection.id}: #{kind} links checked: " \
115
+ "#{found} found (#{result[:review].size} to review), " \
116
+ "#{result[:missing].size} missing")
117
+ QubeRails.config.connection_events_class.new(connection).links_checked(
118
+ kind: kind, found: found, relinked: result[:relinked], review: result[:review],
119
+ missing: result[:missing], stale_left: connection.stale_links.count
120
+ )
121
+ end
122
+
123
+ # The check for one kind, as its own class (Request keys a request by record and SLUG).
124
+ def self.for(kind)
125
+ kind = kind.to_s
126
+ raise ArgumentError, "QuBe Sync: no kind #{kind.inspect} to check" unless kind.match?(/\A[a-z0-9_]+\z/)
127
+
128
+ @kinds ||= {}
129
+ @kinds[kind] ||= Class.new(self) do
130
+ const_set(:KIND, kind)
131
+ const_set(:SLUG, "#{SLUG_PREFIX}#{kind}")
132
+ const_set(:OPERATION, "#{kind}.query")
133
+ def self.name
134
+ "QubeRails::LinkCheck(#{self::KIND})"
135
+ end
136
+ end
137
+ end
138
+
139
+ def self.for_slug(slug)
140
+ self.for(slug.to_s.delete_prefix(SLUG_PREFIX))
141
+ end
142
+
143
+ def self.queue(_record, connection)
144
+ return nil unless connection.connected? && kind_links(connection).exists?
145
+ return nil unless id_key
146
+
147
+ super(connection, connection)
148
+ end
149
+
150
+ def self.kind_links(connection)
151
+ connection.stale_links.where(kind: self::KIND)
152
+ end
153
+
154
+ def self.id_key
155
+ LinkCheck.id_param(self::KIND)
156
+ end
157
+
158
+ # The ids asked about: up to BATCH of the kind's stale links.
159
+ def params
160
+ ids = self.class.kind_links(connection).order(:id).limit(BATCH).pluck(:qb_id)
161
+ { self.class.id_key.to_sym => ids }
162
+ end
163
+
164
+ def connection
165
+ queued_request.connection
166
+ end
167
+
168
+ # The answer settles each id it asked about that's still stale.
169
+ def answered(event)
170
+ @settled = settle(event)
171
+ end
172
+
173
+ # Every page is in (one: a query by id isn't paged): the app hears, and the next batch goes.
174
+ def done
175
+ result = @settled
176
+ # An answer from the old file: ask the new one.
177
+ @next = true if result.nil? && from_old_file?
178
+ return unless result
179
+
180
+ @next = true
181
+ LinkCheck.report(connection, self.class::KIND, result)
182
+ end
183
+
184
+ # The links stay stale, unused: a held record queues the check again after RETRY_AFTER (revive).
185
+ def failed(event)
186
+ log_event(event)
187
+ end
188
+
189
+ # A next batch that can't be queued now is queued again by revive.
190
+ def handle(event)
191
+ super
192
+ return unless @next
193
+
194
+ begin
195
+ self.class.queue(connection, connection)
196
+ rescue Backend::APIError, *Backend::NETWORK_ERRORS => e
197
+ QubeRails.logger.warn("QuBe Sync: connection #{connection.id}: couldn't queue its next " \
198
+ "#{self.class::KIND} link check (#{e.class})")
199
+ end
200
+ end
201
+
202
+ private
203
+
204
+ # nil when the answer isn't one it can trust (an error, rows it didn't ask for, an odd shape, or
205
+ # an answer from a file the connection has switched from): nothing is settled.
206
+ def settle(event)
207
+ if from_old_file?
208
+ QubeRails.logger.warn("QuBe Sync: connection #{connection.id}: #{self.class::KIND} link check " \
209
+ "#{queued_request.id} was queued before its company file changed; nothing settled")
210
+ return nil
211
+ end
212
+
213
+ key = self.class.id_key
214
+ asked = Array((queued_request.params || {})[key]).map(&:to_s)
215
+ found = found_rows(event, key, asked)
216
+ return nil unless found
217
+
218
+ # A missing id makes QuickBooks warn 500, naming only the first one, but every id it has
219
+ # still comes back: one not in the answer isn't in the file.
220
+ result = { relinked: [], review: [], missing: [] }
221
+ now = Time.now
222
+ asked.each do |qb_id|
223
+ link = self.class.kind_links(connection).find_by(qb_id: qb_id)
224
+ next unless link # settled already: a redelivery, or linked again by a run since
225
+
226
+ record = found[qb_id]
227
+ if record
228
+ keep(link, record, result)
229
+ else
230
+ link.update!(stale_since: nil, missing_since: now)
231
+ result[:missing] << link
232
+ end
233
+ end
234
+ result
235
+ end
236
+
237
+ def from_old_file?
238
+ changed_at = connection.company_file_changed_at
239
+ !changed_at.nil? && queued_request.created_at < changed_at
240
+ end
241
+
242
+ def found_rows(event, key, asked)
243
+ answer = event.response_json
244
+ data = answer.is_a?(Hash) && answer["status"] == "success" ? answer["data"] : nil
245
+ rows = data.nil? ? [] : Array(data)
246
+ unless data.is_a?(Array) && rows.all? { |row| row.is_a?(Hash) && asked.include?(row[key].to_s) }
247
+ QubeRails.logger.warn("QuBe Sync: connection #{connection.id}: #{self.class::KIND} link check " \
248
+ "answered unexpectedly; nothing settled, its links stay stale")
249
+ return nil
250
+ end
251
+
252
+ rows.to_h { |row| [row[key].to_s, row] }
253
+ end
254
+
255
+ # An id is stamped with its record's creation time, so finding it only says the files share an
256
+ # origin. The same name (or no name kept) keeps it; another name may be a repurposed record.
257
+ def keep(link, record, result)
258
+ theirs = self.class.id_key == "txn_id" ? record["ref_number"] : record["full_name"] || record["name"]
259
+ if link.name.nil? || normal(link.name) == normal(theirs)
260
+ link.update!(stale_since: nil, missing_since: nil,
261
+ edit_sequence: record["edit_sequence"] || link.edit_sequence)
262
+ result[:relinked] << link
263
+ else
264
+ link.update!(stale_since: nil, review_since: Time.now, review_name: theirs.to_s,
265
+ edit_sequence: record["edit_sequence"] || link.edit_sequence)
266
+ result[:review] << { link: link, record: link.record, old_name: link.name, new_name: theirs.to_s }
267
+ end
268
+ end
269
+
270
+ def normal(name)
271
+ name.to_s.strip.squeeze(" ").downcase
272
+ end
273
+ end
274
+ end
@@ -62,6 +62,7 @@ module QubeRails
62
62
  end
63
63
 
64
64
  raise_realtime_required(connection) if connection.standard?
65
+ connection.wait_for_link_check!(record, name)
65
66
 
66
67
  run, input_error = claim_run(record, connection)
67
68
  raise input_error if input_error
@@ -40,90 +40,68 @@ module QubeRails
40
40
  arrange
41
41
  end
42
42
 
43
- # The choices by where they show: picks (option rows), forms (a section each, "or" between),
44
- # then exits (a footer row, cancel last). plain? when there's neither a pick nor a form: one
45
- # row, the first choice primary.
43
+ # The choices by where they show: picks (option rows), the search boxes under offered records
44
+ # (searches), declines beside them (alongside), forms (a section each, "or" between), forms
45
+ # behind "or <its label>…" (disclosed), then exits (a footer row, cancel last). plain? when
46
+ # there's neither a pick nor a form: one row, the first choice primary.
47
+ # The picks are the offered records, a slot per search box for its picked match (hidden until
48
+ # the script fills it), then the rest.
46
49
  def picks
47
- choices.select { |c| c.kind == :pick }
50
+ offered = choices.select { |c| c.kind == :pick && c.role == "pick" }
51
+ offered + searches.map { |c| PickedView.new(c) } + choices.select { |c| c.kind == :pick && c.role != "pick" }
48
52
  end
49
53
 
50
- # The forms shown as sections. In a chain (chain?) the search ones are its search branch.
51
54
  def forms
52
- choices.select { |c| c.kind == :form }
55
+ choices.select { |c| c.kind == :form && !searches.include?(c) && !disclosed.include?(c) }
53
56
  end
54
57
 
55
- def exits
56
- choices.select { |c| c.kind == :exit }.partition { |c| !c.cancel? }.flatten
57
- end
58
-
59
- def plain?
60
- picks.empty? && forms.empty?
58
+ # With records offered, a search is a box under them; its picked match becomes a row.
59
+ def searches
60
+ @searches || []
61
61
  end
62
62
 
63
- # The one form whose button row also holds the exits (cancel left, the rest beside its
64
- # submit): a question with no picks, one form, and exits without descriptions; in a chain, its
65
- # one search. Else nil, and the exits have a footer row of their own.
66
- def joined_form
67
- candidates = if chain? then forms.select { |c| c.role == "search" }
68
- elsif picks.empty? then forms
69
- else []
70
- end
71
- return nil unless candidates.size == 1 && exits.none?(&:description)
72
-
73
- candidates.first
63
+ # A decline beside offered records with no row of its own ("None of them: add it again"): a
64
+ # button just under them, weighing the same.
65
+ def alongside
66
+ @alongside || []
74
67
  end
75
68
 
76
- # The exits a joined form's row holds: in a chain, decline and cancel (the search's branch).
77
- def joined_exits
78
- chain? ? exits.select { |c| %w[decline cancel].include?(c.role) } : exits
69
+ # The forms after a promoted row (a name clash's rename), each behind "or <its label>…".
70
+ def disclosed
71
+ @disclosed || []
79
72
  end
80
73
 
81
- # Offered records with a search: a chain, shown a branch at a time. The offered records come
82
- # first with "Not this one" / "None of these", which swaps them for the search (README, "Choices").
83
- def chain?
84
- matches? && choices.any? { |c| c.role == "search" }
74
+ def exits
75
+ choices.select { |c| c.kind == :exit && !alongside.include?(c) }.partition { |c| !c.cancel? }.flatten
85
76
  end
86
77
 
87
- # The branch a chain shows as the page loads: :search when its search's answer was just
88
- # refused, else :offered. nil when it isn't a chain.
89
- def branch
90
- return nil unless chain?
91
-
92
- choices.any? { |c| c.role == "search" && c.id == refused_choice } ? :search : :offered
78
+ def plain?
79
+ picks.empty? && forms.empty?
93
80
  end
94
81
 
95
- # The branch a piece of a chain belongs to ("offered" or "search", its data-qube-branch-part):
96
- # a search form, or the picks (:picks), another form, or the footer (:footer) when the search's
97
- # row holds the exits. nil outside a chain, and for what both branches show.
98
- def branch_part(piece)
99
- return nil unless chain?
100
-
101
- case piece
102
- when :picks then "offered"
103
- when :footer then joined_form ? "offered" : nil
104
- when ChoiceView
105
- return nil unless piece.kind == :form
106
-
107
- piece.role == "search" ? "search" : "offered"
108
- end
109
- end
82
+ # The one form whose button row also holds the exits (cancel left, the rest beside its
83
+ # submit): a question with no picks, one form, and exits without descriptions. Else nil, and
84
+ # the exits have a footer row of their own.
85
+ def joined_form
86
+ return nil unless picks.empty? && forms.size == 1 && exits.none?(&:description)
110
87
 
111
- # Whether that part is on show as the page loads.
112
- def shown_part?(part)
113
- part.nil? || part == branch.to_s
88
+ forms.first
114
89
  end
115
90
 
116
- # The count "None of these" and its way back say ("Not this one" for one).
91
+ # How many records QuBe Sync offers.
117
92
  def offered_count
118
- picks.count { |c| c.role == "pick" }
93
+ choices.count { |c| c.kind == :pick && c.role == "pick" }
119
94
  end
120
95
 
121
- # Whether an "or" goes before form n: another form before it in its branch, or the picks.
122
- def divided?(choice, n)
123
- return n.positive? || picks.any? unless chain?
96
+ # Whether an "or" goes before form n: another form before it, or the picks.
97
+ def divided?(_choice, n)
98
+ n.positive? || picks.any?
99
+ end
124
100
 
125
- part = branch_part(choice)
126
- forms.first(n).any? { |c| branch_part(c) == part } || (part == "offered" && picks.any?)
101
+ # A label as it reads after "or": its first letter lowercased.
102
+ def mid_sentence(label)
103
+ text = label.to_s
104
+ text.empty? ? "" : text[0].downcase + text[1..-1]
127
105
  end
128
106
 
129
107
  # Whether QuBe Sync said each choice's role (prompt.choices[].role): then the picks are the
@@ -133,7 +111,7 @@ module QubeRails
133
111
  end
134
112
 
135
113
  def matches?
136
- picks.any? { |c| c.role == "pick" }
114
+ offered_count.positive?
137
115
  end
138
116
 
139
117
  # One of the engine's own words for this question (question.<key> in the locale files). The one
@@ -149,73 +127,64 @@ module QubeRails
149
127
 
150
128
  private
151
129
 
130
+ # Kinds and button styles. With roles: the offered records are picks, the first the one
131
+ # primary action; a search is a form; decline and cancel are exits; an answer shows by its
132
+ # shape. Without roles, every choice by its shape. Offered records beside a decline weigh the
133
+ # same as it; a promoted row (a name clash's "Use the existing record") leads, the forms after
134
+ # it behind "or <its label>…".
152
135
  def arrange
153
- roles? ? arrange_by_role : arrange_by_shape
154
- end
155
-
156
- # By role: the offered records are picks, the first the one primary action; a search is a form,
157
- # secondary; decline and cancel are exits. An answer shows by its shape, as without roles.
158
- def arrange_by_role
159
- @choices.each do |c|
160
- kind = case c.role
161
- when "pick" then :pick
162
- when "search" then :form
163
- when "decline", "cancel" then :exit
164
- else c.fields.any? ? :form : :exit
165
- end
166
- c.arrange(kind, nil)
167
- end
168
- promote_rows
169
- offered = @choices.select { |c| c.role == "pick" }
136
+ roles = roles?
137
+ @choices.each { |c| c.arrange(roles ? kind_by_role(c) : c.kind, nil) }
138
+ promoted = promote_rows
139
+ offered = @choices.select { |c| c.kind == :pick && c.role == "pick" }
170
140
  all_forms = @choices.select { |c| c.kind == :form }
171
- plain = picks.empty? && all_forms.empty?
172
- primary = offered.first || (plain ? @choices.find { |c| !c.cancel? } : all_forms.find { |c| c.role != "search" } || all_forms.first)
141
+ plain = @choices.none? { |c| c.kind == :pick } && all_forms.empty?
142
+ promoted_first = promoted.first
143
+ primary = offered.first || promoted_first ||
144
+ (plain ? @choices.find { |c| !c.cancel? } : all_forms.find { |c| c.role != "search" } || all_forms.first)
145
+ level = offered.any? && @choices.any? { |c| c.role == "decline" }
173
146
  @choices.each do |choice|
174
- style = if choice.kind == :pick then (offered.include?(choice) ? button_style(choice, primary) : promoted_style(choice))
175
- elsif choice.equal?(primary) || (choice.role == "search" && chain?) then :primary
147
+ kind = choice.kind
148
+ style = if kind == :pick then (offered.include?(choice) || promoted.include?(choice) ? button_style(choice, primary) : nil)
149
+ elsif choice.equal?(primary) || (kind == :form && promoted_first) then :primary
176
150
  elsif choice.cancel? then :ghost
177
151
  else :secondary
178
152
  end
179
- choice.arrange(choice.kind, style)
153
+ if level && choice.role == "decline"
154
+ kind = :pick if choice.row?
155
+ style = :secondary
156
+ elsif level && offered.include?(choice)
157
+ style = :secondary
158
+ end
159
+ choice.arrange(kind, style)
160
+ end
161
+ @alongside = level ? @choices.select { |c| c.role == "decline" && c.kind == :exit } : []
162
+ @searches = offered.any? ? @choices.select { |c| c.kind == :form && c.role == "search" } : []
163
+ @searches.each { |c| c.fields.each(&:inline!) }
164
+ @disclosed = promoted_first ? @choices.select { |c| c.kind == :form && c.role != "search" } : []
165
+ end
166
+
167
+ def kind_by_role(choice)
168
+ case choice.role
169
+ when "pick" then :pick
170
+ when "search" then :form
171
+ when "decline", "cancel" then :exit
172
+ else choice.fields.any? ? :form : :exit
180
173
  end
181
- end
182
-
183
- # A choice promoted to an option row ends in a secondary "Use this one", as an offered
184
- # record's does, not a bare link beside the form's filled button.
185
- def promoted_style(choice)
186
- Array(@promoted).include?(choice) ? :secondary : nil
187
174
  end
188
175
 
189
176
  def button_style(choice, primary)
190
177
  choice.equal?(primary) ? :primary : :secondary
191
178
  end
192
179
 
193
- # Kinds and button styles from each choice's shape (a prompt without roles). One filled button
194
- # at most: the first form's submit, or in a plain question the first choice.
195
- def arrange_by_shape
196
- promote_rows
197
- primary = plain? ? @choices.find { |c| !c.cancel? } : forms.first
198
- @choices.each do |choice|
199
- style = if choice.kind == :pick then promoted_style(choice)
200
- elsif choice.equal?(primary) then :primary
201
- elsif choice.cancel? then :ghost
202
- else :secondary
203
- end
204
- choice.arrange(choice.kind, style)
205
- end
206
- end
207
-
208
- # With no picks but a form, a plain choice before the first form (name clash's "Use the
209
- # existing record") is an option row too.
180
+ # With no picks but a form, a plain choice before the first form (a name clash's "Use the
181
+ # existing record") is an option row too. Returns those.
210
182
  def promote_rows
211
- return if @choices.any? { |c| c.kind == :pick }
212
- return unless (first_form = @choices.index { |c| c.kind == :form })
213
-
214
- @choices.first(first_form).each do |c|
215
- next if c.cancel? || %w[decline cancel].include?(c.role)
183
+ return [] if @choices.any? { |c| c.kind == :pick }
184
+ return [] unless (first_form = @choices.index { |c| c.kind == :form })
216
185
 
186
+ @choices.first(first_form).reject { |c| c.cancel? || %w[decline cancel].include?(c.role) }.each do |c|
217
187
  c.arrange(:pick, nil)
218
- (@promoted ||= []) << c
219
188
  end
220
189
  end
221
190
  end
@@ -226,17 +195,21 @@ module QubeRails
226
195
  # One of a select's options.
227
196
  OptionView = Struct.new(:value, :label)
228
197
 
198
+ # One fact of a record a choice is about ("Balance", "1,250.00"): label and value side by side.
199
+ FactView = Struct.new(:label, :value)
200
+
229
201
  # One thing the user can pick: a form of its own, posting choice=<id> and data[...] for its
230
202
  # fields to the question's action_url.
231
203
  class ChoiceView
232
204
  ROLES = %w[pick search decline cancel answer].freeze
233
205
 
234
- attr_reader :id, :label, :detail, :description, :fields, :index, :action_url, :kind, :style, :role
206
+ attr_reader :id, :label, :title, :action, :detail, :lines, :facts, :description, :fields, :index, :action_url,
207
+ :kind, :style, :role
235
208
 
236
- # The detail's parts (QuBe Sync joins them with " · "), each but the last ending in its " ·",
237
- # so a line breaks between parts and never starts with the separator.
238
- def detail_parts
239
- parts = detail.to_s.split(" · ")
209
+ # A text's parts (QuBe Sync joins them with " · "), each but the last ending in its " ·", so a
210
+ # line breaks between parts and never starts with the separator. The detail's by default.
211
+ def detail_parts(text = detail)
212
+ parts = text.to_s.split(" · ")
240
213
  parts.each_with_index.map { |part, i| i < parts.size - 1 ? "#{part} ·" : part }
241
214
  end
242
215
 
@@ -245,7 +218,15 @@ module QubeRails
245
218
  # QuBe Sync's role for it, nil when the prompt has none; one this version doesn't know is answer.
246
219
  @role = (ROLES.include?(choice["role"]) ? choice["role"] : "answer") if choice.key?("role")
247
220
  @label = choice["label"].to_s
221
+ # A choice about one record can say what it is as a row: title in place of its label, action
222
+ # as its button, lines and facts in place of detail.
223
+ @title = presence(choice["title"])
224
+ @action = presence(choice["action"])
248
225
  @detail = presence(choice["detail"])
226
+ @lines = Array(choice["lines"]).map { |line| presence(line) }.compact
227
+ @facts = Array(choice["facts"]).select { |f| f.is_a?(Hash) }.map do |f|
228
+ FactView.new(presence(f["label"]), presence(f["value"]))
229
+ end.select { |f| f.label && f.value }
249
230
  @description = presence(choice["description"])
250
231
  @index = index
251
232
  @action_url = question.action_url
@@ -290,6 +271,11 @@ module QubeRails
290
271
  "qube-#{@token}-choice-#{index}"
291
272
  end
292
273
 
274
+ # The id of an offered record's name, which its button is described by.
275
+ def label_id
276
+ "qube-#{@token}-pick-#{index}#{"-picked" if slot?}"
277
+ end
278
+
293
279
  # Whether one of its fields is a rows field (which needs the behaviour script).
294
280
  def rows?
295
281
  fields.any? { |f| f.type == "rows" }
@@ -305,6 +291,26 @@ module QubeRails
305
291
  @refused
306
292
  end
307
293
 
294
+ # Whether it says what it is as a row of its own (title, action, lines or facts).
295
+ def row?
296
+ !title.nil? || !action.nil? || lines.any? || facts.any?
297
+ end
298
+
299
+ # The hidden data[...] inputs its pick's form posts (a picked match's value).
300
+ def data
301
+ {}
302
+ end
303
+
304
+ # Whether it's a slot the script fills (a search box's picked match), hidden until then.
305
+ def slot?
306
+ false
307
+ end
308
+
309
+ protected
310
+
311
+ # The question's token, for a picked row made from this search.
312
+ attr_reader :token
313
+
308
314
  private
309
315
 
310
316
  def presence(value)
@@ -313,6 +319,34 @@ module QubeRails
313
319
  end
314
320
  end
315
321
 
322
+ # The row a search box under offered records shows its picked match in: an option row whose
323
+ # "Use this one" answers the search's choice with the match. Rendered empty and hidden; the
324
+ # script fills it (a second pick replaces the first).
325
+ class PickedView < ChoiceView
326
+ def initialize(search)
327
+ @search = search
328
+ @id = search.id
329
+ @role = search.role
330
+ @label = ""
331
+ @lines = []
332
+ @facts = []
333
+ @fields = []
334
+ @index = search.index
335
+ @token = search.token
336
+ @action_url = search.action_url
337
+ @kind = :pick
338
+ @style = :secondary
339
+ end
340
+
341
+ def data
342
+ @search.fields.select { |f| f.type == "search" }.map { |f| [f.input_name, ""] }.to_h
343
+ end
344
+
345
+ def slot?
346
+ true
347
+ end
348
+ end
349
+
316
350
  # One input: a choice's field, or a field of a rows field's row.
317
351
  # type is "text", "number", "boolean", "select", "search" or "rows"; partial is the piece that
318
352
  # renders it (qube_rails/question/fields/_<type>).
@@ -383,6 +417,24 @@ module QubeRails
383
417
  @optional = optional.nil? ? !required : optional
384
418
  end
385
419
 
420
+ # A search box under offered records: never required (its pick is a row of its own), and it
421
+ # says "Search QuickBooks…".
422
+ def inline!
423
+ @inline = true
424
+ end
425
+
426
+ def inline?
427
+ @inline == true
428
+ end
429
+
430
+ def required
431
+ @required && !inline?
432
+ end
433
+
434
+ def placeholder
435
+ inline? ? QubeRails.t("question.search_quickbooks") : nil
436
+ end
437
+
386
438
  # Whether it may be left empty: its label says "(optional)". A rows cell's column decides it,
387
439
  # though a hidden cell isn't required in the markup yet.
388
440
  def optional?