qube_rails 0.2.0 → 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 (66) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +321 -0
  3. data/README.md +406 -76
  4. data/app/assets/javascripts/qube_rails/question.js +469 -43
  5. data/app/assets/stylesheets/qube_rails.css +1349 -912
  6. data/app/controllers/qube_rails/connections_controller.rb +42 -9
  7. data/app/controllers/qube_rails/questions_controller.rb +39 -7
  8. data/app/controllers/qube_rails/runs_controller.rb +4 -3
  9. data/app/controllers/qube_rails/storyboard_controller.rb +1 -1
  10. data/app/models/qube_rails/connection.rb +131 -9
  11. data/app/models/qube_rails/quickbooks_record.rb +22 -0
  12. data/app/models/qube_rails/run.rb +28 -10
  13. data/app/views/qube_rails/_error.html.erb +2 -2
  14. data/app/views/qube_rails/_manage_connection.html.erb +19 -0
  15. data/app/views/qube_rails/_question.html.erb +4 -1
  16. data/app/views/qube_rails/question/_choice.html.erb +34 -11
  17. data/app/views/qube_rails/question/_disclosure.html.erb +7 -0
  18. data/app/views/qube_rails/question/_exit_button.html.erb +8 -0
  19. data/app/views/qube_rails/question/_field.html.erb +4 -3
  20. data/app/views/qube_rails/question/_footer.html.erb +12 -4
  21. data/app/views/qube_rails/question/_inline_search.html.erb +12 -0
  22. data/app/views/qube_rails/question/_pick.html.erb +29 -6
  23. data/app/views/qube_rails/question/_picks.html.erb +2 -1
  24. data/app/views/qube_rails/question/_question.html.erb +31 -7
  25. data/app/views/qube_rails/question/_submit.html.erb +9 -0
  26. data/app/views/qube_rails/question/fields/_boolean.html.erb +2 -2
  27. data/app/views/qube_rails/question/fields/_number.html.erb +2 -2
  28. data/app/views/qube_rails/question/fields/_rows.html.erb +17 -4
  29. data/app/views/qube_rails/question/fields/_search.html.erb +6 -3
  30. data/app/views/qube_rails/question/fields/_select.html.erb +6 -5
  31. data/app/views/qube_rails/question/fields/_text.html.erb +2 -2
  32. data/app/views/qube_rails/question/rows/_segmented.html.erb +3 -1
  33. data/app/views/qube_rails/run_status/_detail.html.erb +5 -1
  34. data/app/views/qube_rails/run_status/_status.html.erb +5 -2
  35. data/app/views/qube_rails/storyboard/show.html.erb +4 -3
  36. data/config/locales/en.yml +30 -1
  37. data/config/routes.rb +2 -0
  38. data/db/migrate/20261031000000_add_qube_connection_type_and_run_headline.rb +12 -0
  39. data/db/migrate/20261124000000_add_qube_company_file_change.rb +17 -0
  40. data/lib/generators/qube_rails/templates/connection_events.rb.tt +17 -1
  41. data/lib/generators/qube_rails/templates/initializer.rb.tt +12 -4
  42. data/lib/qube_rails/configuration.rb +5 -2
  43. data/lib/qube_rails/connection_events.rb +70 -7
  44. data/lib/qube_rails/engine.rb +1 -0
  45. data/lib/qube_rails/link_check.rb +274 -0
  46. data/lib/qube_rails/operation.rb +116 -32
  47. data/lib/qube_rails/question_view.rb +293 -35
  48. data/lib/qube_rails/request.rb +2 -0
  49. data/lib/qube_rails/rows_view.rb +18 -5
  50. data/lib/qube_rails/run_status_view.rb +12 -7
  51. data/lib/qube_rails/storyboard/ask_about_add.json +9 -11
  52. data/lib/qube_rails/storyboard/choose.json +10 -7
  53. data/lib/qube_rails/storyboard/enum_select.json +5 -4
  54. data/lib/qube_rails/storyboard/missing_record.json +11 -14
  55. data/lib/qube_rails/storyboard/name_clash.json +51 -21
  56. data/lib/qube_rails/storyboard/near_match.json +18 -15
  57. data/lib/qube_rails/storyboard/number_boolean.json +5 -4
  58. data/lib/qube_rails/storyboard/record_search.json +15 -16
  59. data/lib/qube_rails/storyboard/refusal.json +15 -18
  60. data/lib/qube_rails/storyboard/rows.json +45 -31
  61. data/lib/qube_rails/storyboard.rb +28 -7
  62. data/lib/qube_rails/sync_status.rb +16 -3
  63. data/lib/qube_rails/version.rb +1 -1
  64. data/lib/qube_rails/view_helpers.rb +4 -2
  65. data/lib/qube_rails.rb +11 -2
  66. metadata +10 -2
@@ -19,6 +19,9 @@ module QubeRails
19
19
  # row is left without a qube_id and the next click picks it up. Until connection.connected
20
20
  # comes, show it as waiting for QuickBooks: the setup doesn't come back here.
21
21
  #
22
+ # type is "realtime" or "standard" (default config.connection_type); any other answers 422.
23
+ # Only a never-connected connection of that type is sent back through setup.
24
+ #
22
25
  # With simulated=1, outside production, it connects a simulated QuickBooks company file
23
26
  # instead, for testing with no Windows computer: a new row whose QuBe Sync connection is
24
27
  # connected as it's made, so connection.connected comes at once, and back to the page the
@@ -28,11 +31,16 @@ module QubeRails
28
31
  return head(:unauthorized) unless account
29
32
  return connect_simulated(account) if simulated_requested?
30
33
 
31
- connection = QubeRails::Connection.owned_by(account).never_connected.first unless params[:new].to_s == "1"
34
+ type = requested_type
35
+ return head(:unprocessable_entity) unless type
36
+
37
+ unless params[:new].to_s == "1"
38
+ connection = QubeRails::Connection.owned_by(account).never_connected.find_by(connection_type: type)
39
+ end
32
40
  return send_to_setup(connection) if connection
33
41
 
34
- send_to_setup(QubeRails::Connection.create!(owner: account, name: connection_name, status: "pending"),
35
- fresh: true)
42
+ send_to_setup(QubeRails::Connection.create!(owner: account, name: connection_name, status: "pending",
43
+ connection_type: type), fresh: true)
36
44
  end
37
45
 
38
46
  # POST /quickbooks/connections/:id/onboarding: sends one of the signed-in account's
@@ -48,6 +56,20 @@ module QubeRails
48
56
  send_to_setup(connection)
49
57
  end
50
58
 
59
+ # POST /quickbooks/connections/:id/company_file: sends the customer to switch one of the
60
+ # signed-in account's connections to another company file (its links.company_file, renewed
61
+ # as onboarding's is). QuBe Sync then sends connection.company_file_changed. A simulated
62
+ # connection, or one QuBe Sync never answered, answers 404, as another account's does.
63
+ def company_file
64
+ account = signed_in_account
65
+ return head(:unauthorized) unless account
66
+
67
+ connection = QubeRails::Connection.owned_by(account).find_by(id: params[:id])
68
+ return head(:not_found) if connection.nil? || connection.qube_id.to_s.empty? || connection.simulated?
69
+
70
+ send_to_setup(connection, link: "company_file")
71
+ end
72
+
51
73
  # What the page says when it can't, as I18n keys under qube_rails (config/locales/en.yml).
52
74
  RUNS_GOING = :"errors.still_syncing"
53
75
  NO_ANSWER = :"errors.disconnect_unreachable"
@@ -74,7 +96,7 @@ module QubeRails
74
96
  private
75
97
 
76
98
  def work_going?(connection)
77
- connection.runs.where.not(state: QubeRails::Run::ENDED_STATES).exists? ||
99
+ connection.runs.where.not(state: QubeRails::Run::ENDED_STATES + %w[realtime_required]).exists? ||
78
100
  connection.queued_requests.where(ended_at: nil).exists?
79
101
  end
80
102
 
@@ -101,6 +123,14 @@ module QubeRails
101
123
  account
102
124
  end
103
125
 
126
+ # The type param, else config.connection_type; nil for anything but realtime or standard.
127
+ def requested_type
128
+ type = params[:type].to_s
129
+ return QubeRails.config.connection_type if type.empty?
130
+
131
+ %w[realtime standard].include?(type) ? type : nil
132
+ end
133
+
104
134
  def simulated_requested?
105
135
  params[:simulated].to_s == "1"
106
136
  end
@@ -109,7 +139,8 @@ module QubeRails
109
139
  def connect_simulated(account)
110
140
  return head(:not_found) if Rails.env.production?
111
141
 
112
- connection = QubeRails::Connection.create!(owner: account, name: connection_name, status: "pending")
142
+ connection = QubeRails::Connection.create!(owner: account, name: connection_name, status: "pending",
143
+ connection_type: "simulated")
113
144
  made = QubeRails.client.create_connection(webhook_url: connection.webhook_url, name: connection.name,
114
145
  type: "simulated")
115
146
  connection.update!(qube_id: made["id"])
@@ -121,8 +152,9 @@ module QubeRails
121
152
  name.empty? ? nil : name[0, 255]
122
153
  end
123
154
 
124
- # fresh: a row this request wrote, which no earlier create can have been made for.
125
- def send_to_setup(connection, fresh: false)
155
+ # fresh: a row this request wrote, which no earlier create can have been made for. link: the
156
+ # connection's link to send them to, else its onboarding (a page QuBe Sync has no link for).
157
+ def send_to_setup(connection, fresh: false, link: "onboarding")
126
158
  # An earlier create that landed before its id was saved: that connection, not a second one.
127
159
  connection.adopt_qube_connection if !fresh && connection.qube_id.to_s.empty?
128
160
  if connection.qube_id
@@ -130,12 +162,13 @@ module QubeRails
130
162
  made = QubeRails.client.regenerate_onboarding(connection.qube_id)
131
163
  else
132
164
  made = QubeRails.client.create_connection(webhook_url: connection.webhook_url, name: connection.name,
133
- type: QubeRails.config.connection_type)
165
+ type: connection.connection_type)
134
166
  connection.update!(qube_id: made["id"])
135
167
  end
136
168
 
137
169
  # 303, so the browser follows the POST with a GET.
138
- redirect_to made.dig("links", "onboarding"), allow_other_host: true, status: :see_other
170
+ target = made.dig("links", link) || made.dig("links", "onboarding")
171
+ redirect_to target, allow_other_host: true, status: :see_other
139
172
  end
140
173
  end
141
174
  end
@@ -17,6 +17,11 @@ module QubeRails
17
17
  class QuestionsController < QubeRails.config.parent_controller.constantize
18
18
  # What the page says when the answer wasn't sent, as an I18n key under qube_rails.
19
19
  CHANGED = :"errors.question_changed"
20
+ # ... and when QuBe Sync says the question was answered or asked again since.
21
+ MOVED_ON = :"errors.question_moved_on"
22
+ # A refused answer's fields kept for the page to fill again: these types, this many characters.
23
+ KEPT_TYPES = %w[text number boolean select].freeze
24
+ KEPT_CHARACTERS = 1000
20
25
 
21
26
  include RunAuthorization
22
27
 
@@ -26,22 +31,24 @@ module QubeRails
26
31
  # links.decisions, and sends them back to the page; when it can't, back with why (the
27
32
  # partial shows it). The question is forgotten once it's
28
33
  # answered, or once QuBe Sync says it was answered or asked again since (a 409, or a 400 such
29
- # as not_awaiting_input); the run's next webhook says what came of it.
34
+ # as not_awaiting_input): either way the run has moved past it, so it reads as running until
35
+ # its next webhook says what came of it. A refusal (422) goes back to the question, with what
36
+ # was typed (flash[:qube_rails_refusal]).
30
37
  def create
31
38
  choices = Array(@question && @question["choices"])
32
39
  choice = choices.find { |c| c["id"] == params[:choice] }
33
40
  return back_with_error(CHANGED) unless choice && @links["decisions"]
34
41
 
35
42
  QubeRails.client.answer(@links["decisions"], choice: choice["id"], data: answer_data(choice))
36
- @operation.answered(@question["token"], taken: true)
43
+ @operation.answered(@question["token"], taken: true, cancelling: cancel?(choice))
37
44
  redirect_back fallback_location: "/", status: :see_other
38
45
  rescue Backend::APIError => e
39
46
  raise unless [400, 409, 422].include?(e.status)
40
47
  # A field QuBe Sync couldn't take: its errors.detail says which.
41
- return back_with_error(refusal(e)) if e.status == 422
48
+ return back_with_refusal(choice, refusal(e)) if e.status == 422
42
49
 
43
- @operation.answered(@question["token"])
44
- back_with_error(CHANGED)
50
+ @operation.answered(@question["token"], taken: true)
51
+ back_with_error(MOVED_ON)
45
52
  end
46
53
 
47
54
  # The matches for a record field, for what your user typed: [{value, label, detail}], at most
@@ -64,7 +71,6 @@ module QubeRails
64
71
 
65
72
  private
66
73
 
67
- # What a search is asked about: q of 2 to 100 characters, a field name of 1 to 100.
68
74
  # A rows field's answer: each row's filled columns, by row key. QuBe Sync drops a column the
69
75
  # row's other answers say doesn't apply, and names any required one left out.
70
76
  def rows_data(field, form)
@@ -74,13 +80,18 @@ module QubeRails
74
80
  columns = field["columns"].to_a.select { |column| row["columns"].to_a.include?(column["name"]) }
75
81
  rows[row["key"]] = columns.each_with_object({}) do |column, values|
76
82
  text = given[column["name"]].to_s.strip
83
+ # A checkbox, as a choice's: true or false (QuBe Sync drops one whose "when" doesn't hold).
84
+ next values[column["name"]] = text == "true" if column["type"] == "boolean"
85
+
77
86
  values[column["name"]] = column["type"] == "number" ? number(text) : text unless text.empty?
78
87
  end
79
88
  end
80
89
  end
81
90
 
91
+ # What a search is asked about: q of 2 to 100 characters, a field name of 1 to 100.
92
+ # Empty browses (the list's first records, as a box is focused); one letter isn't a search.
82
93
  def searchable?(q, field)
83
- q.length.between?(2, 100) && field.length.between?(1, 100)
94
+ (q.empty? || q.length.between?(2, 100)) && field.length.between?(1, 100)
84
95
  end
85
96
 
86
97
  def find_question
@@ -117,10 +128,31 @@ module QubeRails
117
128
  end
118
129
  end
119
130
 
131
+ # A cancel: its role, or without roles its id (as ChoiceView#cancel? reads it).
132
+ def cancel?(choice)
133
+ choice.key?("role") ? choice["role"] == "cancel" : choice["id"] == "cancel"
134
+ end
135
+
120
136
  def number(text)
121
137
  text.match?(/\A-?\d+\z/) ? text.to_i : Float(text, exception: false) || text
122
138
  end
123
139
 
140
+ # Back to the question with why it was refused and what was typed in its own simple fields
141
+ # (not a search's pick or a rows field), when that fits a cookie session.
142
+ def back_with_refusal(choice, message)
143
+ form = params.fetch(:data, {})
144
+ values = choice["fields"].to_a.each_with_object({}) do |field, kept|
145
+ next unless KEPT_TYPES.include?(FieldView.type_of(field, record_type: "search"))
146
+
147
+ text = form[field["name"]]
148
+ kept[field["name"].to_s] = text if text.is_a?(String) && !text.empty?
149
+ end
150
+ values = {} if values.sum { |name, text| name.length + text.length } > KEPT_CHARACTERS
151
+ flash[:qube_rails_refusal] = { "token" => @question["token"].to_s, "choice" => choice["id"].to_s,
152
+ "message" => message, "values" => values }
153
+ redirect_back fallback_location: "/", status: :see_other
154
+ end
155
+
124
156
  # What QuBe Sync said was wrong with an answer, in words (its errors.detail).
125
157
  def refusal(error)
126
158
  detail = JSON.parse(error.body.to_s).dig("errors", "detail")
@@ -2,7 +2,8 @@
2
2
 
3
3
  module QubeRails
4
4
  # POST /qube/runs/<run id>/retry_start, from the run status partial's "Try sending again"
5
- # button: sends a start QuBe Sync never confirmed (a run still "starting") again, with the same
5
+ # button: sends a start QuBe Sync never confirmed (a run still "starting", or one refused as
6
+ # "realtime_required") again, with the same
6
7
  # reference as its Idempotency-Key (QubeRails::Run#retry_start!), so a start that did land
7
8
  # answers with its run rather than making another. Behind your sign-in and CSRF, as your
8
9
  # ApplicationController (config.parent_controller) is, and config.authorize_question decides
@@ -19,11 +20,11 @@ module QubeRails
19
20
  def retry_start
20
21
  run, = authorized_run("a start retry")
21
22
  return head(:not_found) unless run
22
- return back_with_error(NOT_STARTING) unless run.state == "starting"
23
+ return back_with_error(NOT_STARTING) unless Operation::RETRYABLE_STATES.include?(run.state)
23
24
 
24
25
  begin
25
26
  run.retry_start!
26
- rescue Backend::APIError, *Backend::NETWORK_ERRORS => e
27
+ rescue Backend::APIError, RealtimeRequired, *Backend::NETWORK_ERRORS => e
27
28
  # Refused (the run is now failed) or no answer again (still unconfirmed): the status on
28
29
  # the page says which.
29
30
  QubeRails.logger.warn("QuBe Sync: run #{run.id}'s start retry didn't go through (#{e.class})")
@@ -28,7 +28,7 @@ module QubeRails
28
28
  end
29
29
 
30
30
  def search
31
- render json: Storyboard.matches(@screen, params[:field], params[:q])
31
+ render json: Storyboard.matches(@screen, params[:field], params[:q], params[:row].presence)
32
32
  end
33
33
 
34
34
  def answer
@@ -12,15 +12,20 @@ module QubeRails
12
12
  # qube_id is QuBe Sync's id for it, nil until QuBe Sync answers the create. status is
13
13
  # "pending" until the setup ends, then "connected", "setup_cancelled" or "stalled" (with
14
14
  # stall_reason), kept up to date by its own webhooks (QubeRails::ConnectionEvents). revision
15
- # is the last of those applied.
15
+ # is the last of those applied. A switch to another company file (connection.company_file_changed)
16
+ # sets it back to "pending", marks its QuickBooks links stale and sets company_file_changed_at
17
+ # and company_file_revision (a late one forgets the file without the status).
18
+ # connection_type is "realtime", "standard" or "simulated": as
19
+ # onboarding made it, then as its events (or refresh_type!) say. Workflows don't run on standard.
16
20
  #
17
21
  # The QuickBooks ids your app learns are kept against it, by list family (link, qb_id_for,
18
- # find_linked), since a ListID is unique only within one list family of one company file.
22
+ # find_linked), since a ListID is unique only within one list family of one company file. After a
23
+ # company file change they're stale (unused) until QubeRails::LinkCheck checks them.
19
24
  class Connection < ApplicationRecord
20
25
  self.table_name = "qube_connections"
21
26
 
22
- # The ones that have never connected, newest first: what Connect sends back through setup
23
- # rather than making another.
27
+ # The ones not connected yet (never set up, set up again after a company file change, or setup
28
+ # cancelled), newest first: what Connect sends back through setup rather than making another.
24
29
  scope :never_connected, -> { where(status: %w[pending setup_cancelled]).order(created_at: :desc, id: :desc) }
25
30
 
26
31
  STATUSES = %w[pending connected setup_cancelled stalled].freeze
@@ -30,7 +35,10 @@ module QubeRails
30
35
  has_many :queued_requests, class_name: "QubeRails::QueuedRequest", inverse_of: :connection
31
36
  has_many :quickbooks_records, class_name: "QubeRails::QuickbooksRecord", inverse_of: :connection
32
37
 
38
+ TYPES = %w[realtime standard simulated].freeze
39
+
33
40
  validates :status, inclusion: { in: STATUSES }
41
+ validates :connection_type, inclusion: { in: TYPES }
34
42
 
35
43
  # The connections owner has, whatever its key's type.
36
44
  # The row, with its runs (and their notifications), its requests and its QuickBooks links: a connection
@@ -64,6 +72,36 @@ module QubeRails
64
72
  status == "connected"
65
73
  end
66
74
 
75
+ # Set up, and not being set up again: connected, or stalled since.
76
+ def set_up?
77
+ %w[connected stalled].include?(status)
78
+ end
79
+
80
+ def simulated?
81
+ connection_type == "simulated"
82
+ end
83
+
84
+ # Whether to offer "Use a different company file": set up, and not simulated (a simulated
85
+ # connection has no file to switch).
86
+ def company_file_switchable?
87
+ set_up? && !qube_id.to_s.empty? && !simulated?
88
+ end
89
+
90
+ # Workflows don't run on it: Operation.start raises RealtimeRequired.
91
+ def standard?
92
+ connection_type == "standard"
93
+ end
94
+
95
+ # Reads its type from QuBe Sync again (GET /api/v2/connections/:id) and saves it: after it's
96
+ # upgraded to realtime in the dashboard, before its next event says so. Returns the type.
97
+ def refresh_type!
98
+ raise NotConnected, "QuBe Sync: connection #{id} has no qube_id yet" if qube_id.to_s.empty?
99
+
100
+ type = QubeRails.client.get_connection(qube_id)["type"].to_s
101
+ update!(connection_type: type) if TYPES.include?(type) && type != connection_type
102
+ connection_type
103
+ end
104
+
67
105
  # Stalled because the Web Connector isn't checking in (the QuickBooks computer is off, or
68
106
  # the Web Connector closed), rather than because it can't open QuickBooks.
69
107
  def not_checking_in?
@@ -102,7 +140,8 @@ module QubeRails
102
140
 
103
141
  QubeRails.logger.info("QuBe Sync: connection #{id} adopted QuBe Sync's connection #{found["id"]}, " \
104
142
  "made for it before its id was saved")
105
- update!(qube_id: found["id"])
143
+ type = found["type"].to_s
144
+ update!({ qube_id: found["id"] }.merge(TYPES.include?(type) ? { connection_type: type } : {}))
106
145
  qube_id
107
146
  end
108
147
 
@@ -140,6 +179,11 @@ module QubeRails
140
179
  row.assign_attributes(kind: kind, qb_id: qb_id, record_type: type, record_id: id)
141
180
  row.edit_sequence = edit_sequence unless edit_sequence.nil?
142
181
  row.name = name unless name.nil?
182
+ # Learned on the file it opens now: no longer the old file's.
183
+ row.stale_since = nil
184
+ row.missing_since = nil
185
+ row.review_since = nil
186
+ row.review_name = nil
143
187
  row.save!
144
188
  row
145
189
  end
@@ -160,7 +204,7 @@ module QubeRails
160
204
  # kind.
161
205
  def qb_id_for(record, kind:)
162
206
  type, id = self.class.key_for(record)
163
- mine = quickbooks_records.where(record_type: type, record_id: id)
207
+ mine = quickbooks_records.current.where(record_type: type, record_id: id)
164
208
  exact = mine.where(kind: kind.to_s).limit(1).pluck(:qb_id).first
165
209
  family = QuickbooksRecord.family_for(kind)
166
210
  return exact if exact || family == "name"
@@ -169,6 +213,72 @@ module QubeRails
169
213
  row && row.qb_id
170
214
  end
171
215
 
216
+ # Its links still to be checked against the company file it opens now.
217
+ def stale_links
218
+ quickbooks_records.stale
219
+ end
220
+
221
+ # Its links the company file it opens now doesn't have: unused, checked again on the next change.
222
+ def missing_links
223
+ quickbooks_records.missing
224
+ end
225
+
226
+ # Its links the new company file has under another name: unused until confirm_link or reject_link.
227
+ def review_links
228
+ quickbooks_records.under_review
229
+ end
230
+
231
+ # While record's link here waits for its check, nothing is sent for it (Operation.start and
232
+ # Request.queue raise LinkBeingChecked), so a record already in QuickBooks isn't added again.
233
+ def checking_link?(record)
234
+ own_links(record).stale.exists?
235
+ end
236
+
237
+ # While record's link here waits for your decision (review_links), nothing is sent for it either
238
+ # (LinkNeedsReview).
239
+ def link_under_review?(record)
240
+ own_links(record).under_review.exists?
241
+ end
242
+
243
+ # A held record first makes sure its links' check is going (LinkCheck.revive), in case the last
244
+ # one failed or was lost.
245
+ def wait_for_link_check!(record, what)
246
+ stale_kinds = own_links(record).stale.distinct.pluck(:kind)
247
+ unless stale_kinds.empty?
248
+ LinkCheck.revive(self, stale_kinds)
249
+ stale_kinds = own_links(record).stale.distinct.pluck(:kind)
250
+ end
251
+ unless stale_kinds.empty?
252
+ raise LinkBeingChecked, "QuBe Sync: #{record.class.name} #{record.id}'s link on connection #{id} is being " \
253
+ "checked on its new company file; send #{what} again once it's settled"
254
+ end
255
+ return unless link_under_review?(record)
256
+
257
+ raise LinkNeedsReview, "QuBe Sync: #{record.class.name} #{record.id}'s link on connection #{id} has another " \
258
+ "name on its new company file; confirm_link or reject_link it, then send #{what} again"
259
+ end
260
+
261
+ # A link under review is the same record after all: current again, with the name QuickBooks has.
262
+ def confirm_link(link)
263
+ link = own_review_link(link)
264
+ link.update!(name: link.review_name.nil? ? link.name : link.review_name, review_since: nil, review_name: nil)
265
+ link
266
+ end
267
+
268
+ # A link under review isn't the same record: kept as missing, so the record is matched by name
269
+ # (or added) when it's next sent.
270
+ def reject_link(link)
271
+ link = own_review_link(link)
272
+ link.update!(review_since: nil, review_name: nil, missing_since: Time.now)
273
+ link
274
+ end
275
+
276
+ # Queues the checks of its stale links (QubeRails::LinkCheck), when it's connected and has any.
277
+ # The engine does this on its events; call it to start them again after a check failed.
278
+ def check_stale_links
279
+ LinkCheck.start(self)
280
+ end
281
+
172
282
  # Where record stands with QuickBooks on this connection for operation (its SLUG): a
173
283
  # QubeRails::SyncStatus, worked out from its runs and its link, never stored.
174
284
  def sync_status(record, operation:)
@@ -203,12 +313,12 @@ module QubeRails
203
313
  row && row.record
204
314
  end
205
315
 
206
- # The row for that QuickBooks id (with its kind, edit_sequence and name), or nil. With a kind,
316
+ # The current (not stale) row for that QuickBooks id (with its kind, edit_sequence and name), or nil. With a kind,
207
317
  # it's looked up in that kind's family; without one, in every family, and an id found in more
208
318
  # than one (the same counter value is a customer and an account) raises ArgumentError, so the
209
319
  # caller says which kind it means.
210
320
  def quickbooks_record(qb_id, kind: nil)
211
- rows = quickbooks_records.where(qb_id: qb_id.to_s)
321
+ rows = quickbooks_records.current.where(qb_id: qb_id.to_s)
212
322
  return rows.find_by(list: QuickbooksRecord.family_for(kind)) if kind
213
323
 
214
324
  only_one(rows, "QuickBooks id #{qb_id}")
@@ -216,6 +326,18 @@ module QubeRails
216
326
 
217
327
  private
218
328
 
329
+ def own_links(record)
330
+ type, id = self.class.key_for(record)
331
+ quickbooks_records.where(record_type: type, record_id: id)
332
+ end
333
+
334
+ def own_review_link(link)
335
+ row = review_links.find_by(id: link.respond_to?(:id) ? link.id : link)
336
+ raise ArgumentError, "QuBe Sync: link #{link.inspect} isn't under review on connection #{id}" unless row
337
+
338
+ row
339
+ end
340
+
219
341
  # The record's own link is a different row from the one holding this qb_id, so it gives way.
220
342
  def replaced?(mine, by:)
221
343
  !mine.nil? && !by.nil? && by.id != mine.id
@@ -257,7 +379,7 @@ module QubeRails
257
379
  # EXISTS a link on this connection for each row of scope's table.
258
380
  def linked_here(scope)
259
381
  model = scope.all.klass
260
- QuickbooksRecord.where(connection_id: id, record_type: model.base_class.name)
382
+ QuickbooksRecord.current.where(connection_id: id, record_type: model.base_class.name)
261
383
  .where("qube_quickbooks_records.record_id = #{id_as_text(model, QuickbooksRecord)}")
262
384
  .arel.exists
263
385
  end
@@ -11,6 +11,11 @@ module QubeRails
11
11
  # own, while the same counter value turns up in several families. So a row is unique by
12
12
  # connection, family and qb_id, and by connection, kind and your record (one contact can be
13
13
  # both a customer and a vendor, as two QuickBooks names).
14
+ #
15
+ # A row with stale_since is the old company file's, after connection.company_file_changed, until
16
+ # QubeRails::LinkCheck looks it up on the new file; one with missing_since wasn't there; one with
17
+ # review_since was, under another name (review_name), and waits for Connection#confirm_link or
18
+ # #reject_link. None of them is used: every reader takes current.
14
19
  class QuickbooksRecord < ApplicationRecord
15
20
  self.table_name = "qube_quickbooks_records"
16
21
 
@@ -21,6 +26,23 @@ module QubeRails
21
26
 
22
27
  before_validation { self.list = self.class.family_for(kind) }
23
28
 
29
+ scope :current, -> { where(stale_since: nil, missing_since: nil, review_since: nil) }
30
+ scope :stale, -> { where.not(stale_since: nil) }
31
+ scope :missing, -> { where.not(missing_since: nil) }
32
+ scope :under_review, -> { where.not(review_since: nil) }
33
+
34
+ def stale?
35
+ !stale_since.nil?
36
+ end
37
+
38
+ def missing?
39
+ !missing_since.nil?
40
+ end
41
+
42
+ def under_review?
43
+ !review_since.nil?
44
+ end
45
+
24
46
  # The list family a kind's ids are unique within: "name" for customers, vendors, employees
25
47
  # and other names; "item" for "item" and every item_* kind; for anything else (an account, a
26
48
  # class, a transaction, a kind this version doesn't know) the kind itself. TxnIDs are taken as
@@ -9,11 +9,14 @@ module QubeRails
9
9
  #
10
10
  # reference is new for every run and sent with it, and every event is checked against it and
11
11
  # the connection's qube_id. revision is the last event applied; state ("starting", then the
12
- # run's own: "running", "awaiting_input", "completed", "failed", "cancelled") and outcome are
12
+ # run's own: "running", "awaiting_input", "completed", "failed", "cancelled"; "cancelling" after
13
+ # your user's cancel, until the next event) and outcome are
13
14
  # the run's as of that event. question and links are the question it's asking, if any, for the
14
- # question partial. input is what the run was started with. A start QuBe Sync refused (a 4xx),
15
+ # question partial. input is what the run was started with. headline is the last event's
16
+ # sentence for a person (shown, never parsed). A start QuBe Sync refused (a 4xx),
15
17
  # or whose input raised, leaves state "failed"; one that got no answer (a timeout, a 5xx, a
16
- # dropped connection) stays "starting", for retry_start!.
18
+ # dropped connection) stays "starting", for retry_start!. One refused as realtime_required is
19
+ # "realtime_required", with that error, and isn't ended: retry_start! sends it once upgraded.
17
20
  class Run < ApplicationRecord
18
21
  self.table_name = "qube_runs"
19
22
 
@@ -80,6 +83,11 @@ module QubeRails
80
83
  state == "failed"
81
84
  end
82
85
 
86
+ # Refused because its connection is standard; retry_start! once it's upgraded.
87
+ def realtime_required?
88
+ state == "realtime_required"
89
+ end
90
+
83
91
  # Cancelled by your app (state "cancelled"), or a chart that ended on its own "cancelled"
84
92
  # outcome (the app chose to stop): neither is a success.
85
93
  def cancelled?
@@ -97,7 +105,7 @@ module QubeRails
97
105
  # or waiting on a question this app never received. Its webhook may have been lost (the app
98
106
  # was down longer than QuBe Sync's retries), so the status offers to send it again.
99
107
  def looks_stuck?
100
- quiet_since?(Time.now - QUIET_AFTER_SECONDS) && (state == "running" || question_missing?)
108
+ quiet_since?(Time.now - QUIET_AFTER_SECONDS) && (%w[running cancelling].include?(state) || question_missing?)
101
109
  end
102
110
 
103
111
  # A start QuBe Sync hasn't confirmed for a minute: send it again with retry_start!.
@@ -117,7 +125,8 @@ module QubeRails
117
125
 
118
126
  # Where it stands, in a few words for a person: "Added to QuickBooks", "Done", "Couldn't
119
127
  # sync", "Cancelled", "Needs your answer", "Sending to QuickBooks", "Still waiting for
120
- # QuickBooks" (a start unconfirmed for a minute) or "Syncing with QuickBooks". Why it failed
128
+ # QuickBooks" (a start unconfirmed for a minute), "Cancelling…" (a cancel posted, no event
129
+ # since) or "Syncing with QuickBooks". Why it failed
121
130
  # or was cancelled is reason_text. The words are I18n's, under qube_rails.status.
122
131
  def summary_text
123
132
  return QubeRails.t("status.cancelled") if cancelled?
@@ -129,10 +138,13 @@ module QubeRails
129
138
  case outcome.to_s
130
139
  when "added" then QubeRails.t("status.added")
131
140
  when "", "completed" then QubeRails.t("status.done")
141
+ when /_with_errors\z/ then QubeRails.t("status.done_with_errors")
132
142
  else QubeRails.t("status.done_with", outcome: humanize(outcome))
133
143
  end
134
144
  when "failed" then QubeRails.t("status.failed")
145
+ when "realtime_required" then error_message.to_s.empty? ? QubeRails.t("status.realtime_required") : error_message
135
146
  when "awaiting_input" then QubeRails.t("status.needs_answer")
147
+ when "cancelling" then QubeRails.t("status.cancelling")
136
148
  else QubeRails.t("status.running")
137
149
  end
138
150
  end
@@ -155,8 +167,14 @@ module QubeRails
155
167
  reason.empty? ? QubeRails.t("status.cancel_reason") : reason
156
168
  end
157
169
 
158
- # A failed run's message: its error's own (a sentence, or the message of a code, message and
159
- # detail), else its outcome in words, or nil.
170
+ # A completed run that ended on an outcome with errors (push_records' pushed_with_errors): some
171
+ # of its records failed, so it needs a look.
172
+ def with_errors?
173
+ state == "completed" && outcome.to_s.end_with?("_with_errors")
174
+ end
175
+
176
+ # A failed run's message: its error's own (a sentence, or the message of {code, type, message,
177
+ # quickbooks_message, hint}, or of 0.2.0's code, message and detail), else its outcome in words, or nil.
160
178
  def error_message
161
179
  text =
162
180
  case error
@@ -170,12 +188,12 @@ module QubeRails
170
188
  outcome.to_s.empty? || outcome == "failed" ? nil : humanize(outcome)
171
189
  end
172
190
 
173
- # The error's detail, when it carries one apart from its message.
191
+ # What to do about the error: its hint, else its detail, when apart from its message.
174
192
  def error_detail
175
193
  return nil unless error.is_a?(Hash)
176
194
 
177
- detail = error["detail"]
178
- detail = detail.to_s.strip
195
+ detail = error["hint"].to_s.strip
196
+ detail = error["detail"].to_s.strip if detail.empty?
179
197
  detail.empty? || detail == error_message ? nil : detail
180
198
  end
181
199
 
@@ -1,7 +1,7 @@
1
1
  <%# A message from one of the engine's routes, shown once. Without a message local it takes
2
2
  flash[:qube_rails_error], for a page without the run partials:
3
3
  render "qube_rails/error"
4
- The question and run status pieces pass theirs (message: nil shows nothing). %>
4
+ The question and run status pieces pass theirs (message: nil shows nothing); id: is optional. %>
5
5
  <% if local_assigns.key?(:message) %>
6
6
  <% message = local_assigns[:message] %>
7
7
  <% else %>
@@ -9,5 +9,5 @@
9
9
  <% flash.delete(:qube_rails_error) %>
10
10
  <% end %>
11
11
  <% if message.present? %>
12
- <p class="<%= qube_classes(:error, "qube-error") %>" role="alert"><%= message %></p>
12
+ <%= tag.p(message, class: qube_classes(:error, "qube-error"), role: "alert", id: local_assigns[:id]) %>
13
13
  <% end %>
@@ -0,0 +1,19 @@
1
+ <%# A set-up connection's actions, for the page that shows its QuickBooks status:
2
+ render "qube_rails/manage_connection", connection: connection
3
+ "Set up QuickBooks again" (a moved computer, a removed Web Connector) and, unless it's
4
+ simulated, "Use a different company file". Nothing while it isn't set up: offer Connect then.
5
+ Both leave for QuBe Sync's setup, so their forms opt out of Turbo. The words are I18n's:
6
+ qube_rails.connection.set_up_again and .use_different_company_file. %>
7
+ <% connection = local_assigns.fetch(:connection) %>
8
+ <% if connection.set_up? %>
9
+ <div class="qube-manage-connection" id="qube-manage-connection-<%= connection.id %>">
10
+ <%= button_to QubeRails.t("connection.set_up_again"), qube_rails.connection_onboarding_path(connection),
11
+ class: qube_classes(:button_secondary, "qube-set-up-again"),
12
+ form: { class: "qube-set-up-again-form", data: { turbo: false } } %>
13
+ <% if connection.company_file_switchable? %>
14
+ <%= button_to QubeRails.t("connection.use_different_company_file"), qube_rails.connection_company_file_path(connection),
15
+ class: qube_classes(:button_secondary, "qube-use-different-company-file"),
16
+ form: { class: "qube-use-different-company-file-form", data: { turbo: false } } %>
17
+ <% end %>
18
+ </div>
19
+ <% end %>
@@ -13,7 +13,10 @@
13
13
  <%= turbo_stream_from(record, :qube_rails) if respond_to?(:turbo_stream_from) %>
14
14
  <% error = flash[:qube_rails_error] %>
15
15
  <% flash.delete(:qube_rails_error) # shown once, by whichever partial comes first %>
16
- <% question = QubeRails::QuestionView.from_run(run, qube_rails, error: error) %>
16
+ <%# A refused answer (422): shown in its question, with what was typed. %>
17
+ <% refusal = flash[:qube_rails_refusal] %>
18
+ <% flash.delete(:qube_rails_refusal) %>
19
+ <% question = QubeRails::QuestionView.from_run(run, qube_rails, error: error, refusal: refusal) %>
17
20
  <% if question %>
18
21
  <%= render "qube_rails/question/question", question: question %>
19
22
  <% else %>