qube_rails 0.2.0 → 0.2.1

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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +216 -0
  3. data/README.md +242 -69
  4. data/app/assets/javascripts/qube_rails/question.js +425 -38
  5. data/app/assets/stylesheets/qube_rails.css +1201 -907
  6. data/app/controllers/qube_rails/connections_controller.rb +23 -6
  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/models/qube_rails/connection.rb +22 -2
  10. data/app/models/qube_rails/run.rb +28 -10
  11. data/app/views/qube_rails/_error.html.erb +2 -2
  12. data/app/views/qube_rails/_question.html.erb +4 -1
  13. data/app/views/qube_rails/question/_choice.html.erb +36 -11
  14. data/app/views/qube_rails/question/_exit_button.html.erb +8 -0
  15. data/app/views/qube_rails/question/_field.html.erb +4 -3
  16. data/app/views/qube_rails/question/_footer.html.erb +19 -5
  17. data/app/views/qube_rails/question/_pick.html.erb +8 -3
  18. data/app/views/qube_rails/question/_picks.html.erb +4 -2
  19. data/app/views/qube_rails/question/_question.html.erb +22 -7
  20. data/app/views/qube_rails/question/_submit.html.erb +9 -0
  21. data/app/views/qube_rails/question/fields/_boolean.html.erb +2 -2
  22. data/app/views/qube_rails/question/fields/_number.html.erb +2 -2
  23. data/app/views/qube_rails/question/fields/_rows.html.erb +17 -4
  24. data/app/views/qube_rails/question/fields/_search.html.erb +3 -1
  25. data/app/views/qube_rails/question/fields/_select.html.erb +6 -5
  26. data/app/views/qube_rails/question/fields/_text.html.erb +2 -2
  27. data/app/views/qube_rails/question/rows/_segmented.html.erb +3 -1
  28. data/app/views/qube_rails/run_status/_detail.html.erb +5 -1
  29. data/app/views/qube_rails/run_status/_status.html.erb +5 -2
  30. data/config/locales/en.yml +23 -1
  31. data/db/migrate/20261031000000_add_qube_connection_type_and_run_headline.rb +12 -0
  32. data/lib/generators/qube_rails/templates/initializer.rb.tt +12 -4
  33. data/lib/qube_rails/configuration.rb +3 -2
  34. data/lib/qube_rails/connection_events.rb +3 -0
  35. data/lib/qube_rails/operation.rb +115 -32
  36. data/lib/qube_rails/question_view.rb +235 -29
  37. data/lib/qube_rails/rows_view.rb +18 -5
  38. data/lib/qube_rails/run_status_view.rb +12 -7
  39. data/lib/qube_rails/storyboard/ask_about_add.json +8 -10
  40. data/lib/qube_rails/storyboard/choose.json +8 -5
  41. data/lib/qube_rails/storyboard/enum_select.json +4 -3
  42. data/lib/qube_rails/storyboard/missing_record.json +10 -13
  43. data/lib/qube_rails/storyboard/name_clash.json +10 -18
  44. data/lib/qube_rails/storyboard/near_match.json +12 -14
  45. data/lib/qube_rails/storyboard/number_boolean.json +4 -3
  46. data/lib/qube_rails/storyboard/record_search.json +14 -15
  47. data/lib/qube_rails/storyboard/refusal.json +10 -18
  48. data/lib/qube_rails/storyboard/rows.json +11 -14
  49. data/lib/qube_rails/storyboard.rb +8 -3
  50. data/lib/qube_rails/sync_status.rb +4 -2
  51. data/lib/qube_rails/version.rb +1 -1
  52. data/lib/qube_rails/view_helpers.rb +4 -2
  53. data/lib/qube_rails.rb +2 -2
  54. metadata +5 -2
@@ -1,12 +1,25 @@
1
1
  <%# A rows field (field.rows, a QubeRails::RowsView): a block per record with the fields it asks,
2
2
  posted as data[<field>][<row key>][<column>]. A field shows only while its "when" holds. "Set
3
- all to:" sets the segmented column on every row, and "Use for all" copies one row's value to
4
- the others (the behaviour script). %>
3
+ all to:" sets the segmented column on every row, and "Use for the other records too" copies one
4
+ row's value to the others' empty field and says so (the behaviour script). With the script, more than one row shows one at a time:
5
+ the data-qube-text-step/-back/-next words and the button classes are for its step line and
6
+ Back / Next. It needs the script: hidden until the script shows it, with a <noscript> line
7
+ saying so. %>
5
8
  <% rows = field.rows %>
6
9
  <% set_all = rows.set_all %>
7
- <div class="<%= qube_classes(:field, "qube-field", "qube-rows-field") %>" data-qube-rows
8
- data-qube-text-use-for-all="<%= QubeRails.t("question.use_for_all", count: "%{count}") %>">
10
+ <noscript><p class="<%= qube_classes(:error, "qube-error") %>"><%= QubeRails.t("question.needs_script") %></p></noscript>
11
+ <div class="<%= qube_classes(:field, "qube-field", "qube-rows-field") %>" data-qube-rows data-qube-needs-script hidden
12
+ data-qube-text-use-for-all-one="<%= QubeRails.t("question.use_for_all", count: 1) %>"
13
+ data-qube-text-use-for-all-other="<%= QubeRails.t("question.use_for_all", count: "%{count}") %>"
14
+ data-qube-text-used-for-all-one="<%= QubeRails.t("question.used_for_all", count: 1) %>"
15
+ data-qube-text-used-for-all-other="<%= QubeRails.t("question.used_for_all", count: "%{count}") %>"
16
+ data-qube-text-step="<%= rows.ui_text(:step, name: "%{name}", position: "%{position}", count: "%{count}") %>"
17
+ data-qube-text-back="<%= QubeRails.t("question.back") %>" data-qube-text-next="<%= QubeRails.t("question.next") %>"
18
+ data-qube-button-class="<%= qube_classes(:button, "qube-choice-button") %>"
19
+ data-qube-button-secondary-class="<%= qube_classes(:button_secondary, "qube-choice-button") %>">
20
+ <% unless rows.label.strip.empty? %>
9
21
  <p class="<%= qube_classes(:label, "qube-rows-label") %>"><%= rows.label %></p>
22
+ <% end %>
10
23
  <% if set_all %>
11
24
  <div class="qube-rows-set-all" data-qube-rows-set-all="<%= set_all.name %>">
12
25
  <span class="qube-rows-set-all-label"><%= QubeRails.t("question.set_all") %></span>
@@ -6,7 +6,8 @@
6
6
  <%= tag.input(type: "search", id: field.dom_id, class: qube_classes(:input, "qube-search-input"), maxlength: 100,
7
7
  autocomplete: "off", required: field.required, disabled: field.disabled,
8
8
  role: "combobox", "aria-autocomplete": "list", "aria-expanded": "false",
9
- "aria-label": (field.labelled? ? nil : field.label), data: { "qube-search-input" => "" }) %>
9
+ "aria-label": (field.labelled? ? nil : field.label), data: { "qube-search-input" => "" },
10
+ **field.aria_invalid) %>
10
11
  <%= tag.input(type: "hidden", name: field.input_name, disabled: field.disabled,
11
12
  class: ["qube-search-value", field.cell? ? "qube-rows-input" : nil].compact.join(" "),
12
13
  data: field.data.merge("qube-search-value" => "")) %>
@@ -19,5 +20,6 @@
19
20
  "qube-text-no-matches" => QubeRails.t("question.no_matches"),
20
21
  "qube-text-searching" => QubeRails.t("question.searching"),
21
22
  "qube-text-search-failed" => QubeRails.t("question.search_failed"),
23
+ "qube-text-search-changed" => QubeRails.t("question.search_changed"),
22
24
  "qube-text-pick-a-match" => QubeRails.t("question.pick_a_match") }.compact) %>
23
25
  <%= render "qube_rails/question/field", field: field, control: control %>
@@ -1,8 +1,9 @@
1
- <%# A fixed list (field.options, each value and label), with a blank first. %>
1
+ <%# A fixed list (field.options, each value and label), with "Choose…" (question.choose) first;
2
+ field.value (a column's default, or what a refused answer had) starts selected. %>
2
3
  <% control = capture do %>
3
- <%= select_tag field.input_name, options_for_select(field.options.map { |o| [o.label, o.value] }),
4
- id: field.dom_id, include_blank: true, required: field.required, disabled: field.disabled,
5
- class: qube_classes(:select, "qube-select", field.cell? ? "qube-rows-input" : nil),
6
- "aria-label": (field.labelled? ? nil : field.label), data: field.data %>
4
+ <%= select_tag field.input_name, options_for_select(field.options.map { |o| [o.label, o.value] }, field.value),
5
+ id: field.dom_id, include_blank: QubeRails.t("question.choose"), required: field.required,
6
+ disabled: field.disabled, class: qube_classes(:select, "qube-select", field.cell? ? "qube-rows-input" : nil),
7
+ "aria-label": (field.labelled? ? nil : field.label), data: field.data, **field.aria_invalid %>
7
8
  <% end %>
8
9
  <%= render "qube_rails/question/field", field: field, control: control %>
@@ -1,7 +1,7 @@
1
1
  <%# A text field. %>
2
2
  <% control = capture do %>
3
- <%= text_field_tag field.input_name, nil, id: field.dom_id, required: field.required, disabled: field.disabled,
3
+ <%= text_field_tag field.input_name, field.value, id: field.dom_id, required: field.required, disabled: field.disabled,
4
4
  class: qube_classes(:input, "qube-input", field.cell? ? "qube-rows-input" : nil),
5
- "aria-label": (field.labelled? ? nil : field.label), data: field.data %>
5
+ "aria-label": (field.labelled? ? nil : field.label), data: field.data, **field.aria_invalid %>
6
6
  <% end %>
7
7
  <%= render "qube_rails/question/field", field: field, control: control %>
@@ -1,11 +1,13 @@
1
1
  <%# A short list (field.options, at most three) in a row as a segmented control: radios posted
2
- as field.input_name, the column's label their group's name for screen readers. %>
2
+ as field.input_name, the column's label their group's name for screen readers; field.value
3
+ (the column's default) starts checked. %>
3
4
  <fieldset class="qube-segmented-field">
4
5
  <legend class="qube-visually-hidden"><%= field.label %></legend>
5
6
  <div class="<%= qube_classes(:segmented, "qube-segmented") %>">
6
7
  <% field.options.each do |option| %>
7
8
  <label class="<%= qube_classes(:segment, "qube-segment") %>">
8
9
  <%= tag.input(type: "radio", name: field.input_name, value: option.value, required: field.required,
10
+ checked: !field.value.nil? && field.value.to_s == option.value.to_s,
9
11
  disabled: field.disabled, class: "qube-segment-input qube-rows-input", data: field.data) %>
10
12
  <span><%= option.label %></span>
11
13
  </label>
@@ -1,4 +1,8 @@
1
- <%# Why a run failed or was cancelled (run_status.reason), then what to do about it (detail). %>
1
+ <%# Why a run failed or was cancelled (run_status.reason), then what to do about it (detail), or
2
+ what an ended run did (headline: QuBe Sync's sentence, shown as it is). %>
3
+ <% if run_status.headline %>
4
+ <p class="<%= qube_classes(:reason, "qube-run-headline") %>"><%= run_status.headline %></p>
5
+ <% end %>
2
6
  <% if run_status.reason %>
3
7
  <p class="<%= qube_classes(:reason, "qube-run-reason") %>"><%= run_status.reason %></p>
4
8
  <% end %>
@@ -1,11 +1,14 @@
1
- <%# A record's status (run_status, a QubeRails::RunStatusView): the error, then the summary, the
1
+ <%# A record's status (run_status, a QubeRails::RunStatusView): the summary, then the error, the
2
2
  failure's detail, why it waits on a stalled connection, and the buttons, or only the error
3
3
  before it's sent. %>
4
+ <% unless run_status.visible? %>
4
5
  <%= render "qube_rails/error", message: run_status.error %>
6
+ <% end %>
5
7
  <% if run_status.visible? %>
6
8
  <div class="<%= qube_classes(:status, run_status.css_class) %>" data-qube-sync-status="<%= run_status.status %>"<% if run_status.stall %> data-qube-stall="<%= run_status.stall %>"<% end %>>
7
9
  <%= render "qube_rails/run_status/summary", run_status: run_status %>
8
- <% if run_status.reason || run_status.detail %>
10
+ <%= render "qube_rails/error", message: run_status.error %>
11
+ <% if run_status.reason || run_status.detail || run_status.headline %>
9
12
  <%= render "qube_rails/run_status/detail", run_status: run_status %>
10
13
  <% end %>
11
14
  <% if run_status.stall %>
@@ -8,7 +8,9 @@ en:
8
8
  added: "Added to QuickBooks"
9
9
  done: "Done"
10
10
  done_with: "Done: %{outcome}"
11
+ done_with_errors: "Done, but some didn't go through"
11
12
  failed: "Couldn't sync"
13
+ realtime_required: "This company file's connection needs an upgrade to realtime before this can sync."
12
14
  not_started: "it couldn't be sent"
13
15
  cancelled: "Cancelled"
14
16
  cancel_reason: "it was stopped before it finished"
@@ -16,6 +18,7 @@ en:
16
18
  starting: "Sending to QuickBooks"
17
19
  unconfirmed: "Still waiting for QuickBooks"
18
20
  running: "Syncing with QuickBooks"
21
+ cancelling: "Cancelling…"
19
22
  quiet: "No update from QuickBooks for a while."
20
23
  check_for_updates: "Check for updates"
21
24
  try_again: "Try sending again"
@@ -35,10 +38,29 @@ en:
35
38
  question_changed: "This question changed after the page loaded, so your answer wasn't sent. The page now shows the latest."
36
39
  answer_refused: "That answer couldn't be used. Check it and try again."
37
40
  answer_refused_with: "That answer couldn't be used: %{detail}"
41
+ question_moved_on: "This question was already answered or has changed, so your answer wasn't sent. If QuickBooks needs anything else, it will ask here."
38
42
  question:
39
43
  set_all: "Set all to:"
40
44
  use_pick: "Use this one"
41
- use_for_all: "Use for all %{count}"
45
+ none_of_these:
46
+ one: "Not this one"
47
+ other: "None of these"
48
+ back_to_offered:
49
+ one: "← Back to the possible match"
50
+ other: "← Back to the %{count} possible matches"
51
+ choose: "Choose…"
52
+ optional: "(optional)"
53
+ needs_script: "Answering this needs JavaScript. Turn it on for this page, or answer from a browser that has it."
54
+ use_for_all:
55
+ one: "Use for the other record too"
56
+ other: "Use for the other %{count} records too"
57
+ used_for_all:
58
+ one: "Also filled in on the other record."
59
+ other: "Also filled in on the other %{count} records."
60
+ search_changed: "This question has changed. Reload the page to see the latest."
61
+ step: "%{position} of %{count}"
62
+ back: "Back"
63
+ next: "Next"
42
64
  or: "or"
43
65
  pick_a_match: "Pick one of the matches."
44
66
  no_matches: "No matches"
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A connection's type ("realtime", "standard" or "simulated"), as onboarding made it and its events
4
+ # say since: Operation.start refuses a standard one before sending anything. Rows from 0.2.0 get
5
+ # "realtime", the default onboarding made then; the connection's next event corrects one that isn't.
6
+ # And a run's headline: its last event's sentence for a person, shown, never parsed.
7
+ class AddQubeConnectionTypeAndRunHeadline < ActiveRecord::Migration[5.2]
8
+ def change
9
+ add_column :qube_connections, :connection_type, :string, null: false, default: "realtime", limit: 20
10
+ add_column :qube_runs, :headline, :text
11
+ end
12
+ end
@@ -48,8 +48,10 @@ QubeRails.configure do |config|
48
48
  # until set.
49
49
  # config.prune_runs_after = 90.days
50
50
 
51
- # Onboarding makes realtime connections: workflows run only on those (billed as realtime).
51
+ # The type Connect makes connections as: "realtime" (workflows run only on those, billed as
52
+ # realtime) or "standard" (for an app that only queues requests). Connect's type param overrides it.
52
53
  # config.connection_type = "realtime"
54
+
53
55
  # How many times QubeRails::WebhookJob runs a delivery whose work raised, with a growing wait,
54
56
  # before it logs an error and raises to your adapter. With Sidekiq, whose own retries follow,
55
57
  # a smaller number (or 1, to leave retries to Sidekiq) avoids retrying twice over.
@@ -61,9 +63,15 @@ QubeRails.configure do |config|
61
63
  # config.dedupe = QubeRails::CacheDedupe.new(Rails.cache, expires_in: 1.day)
62
64
 
63
65
  # Your CSS framework's classes for the engine's screens, by piece, added beside their qube-
64
- # classes (pieces: QubeRails::Configuration::UI_PIECES; see the README's "Styling"):
65
- # config.ui_classes = { button: "btn btn-primary", button_secondary: "btn btn-link",
66
- # input: "form-control", select: "form-select", label: "form-label" }
66
+ # classes (pieces: QubeRails::Configuration::UI_PIECES; see the README's "Styling"). Tailwind:
67
+ # config.ui_classes = {
68
+ # button: "rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white hover:bg-indigo-500",
69
+ # button_secondary: "rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 ring-1 ring-inset ring-gray-300 hover:bg-gray-50",
70
+ # input: "rounded-md border border-gray-300 px-3 py-2 text-sm focus:border-indigo-600 focus:outline-none",
71
+ # select: "rounded-md border border-gray-300 px-3 py-2 text-sm",
72
+ # label: "text-sm font-medium text-gray-900",
73
+ # error: "rounded-md bg-red-50 px-3 py-2 text-sm text-red-700"
74
+ # }
67
75
 
68
76
  # GET /qube/storyboard: every screen with sample data, in your layout. On in development.
69
77
  # config.storyboard = Rails.env.development?
@@ -39,12 +39,13 @@ module QubeRails
39
39
  question message details choice choice_detail choice_description field label input select checkbox
40
40
  button button_secondary search search_results search_result status summary detail error
41
41
  rows row row_header segmented segment row_fields use_for_all stall
42
- picks pick pick_detail pick_action reason button_ghost choice_footer choice_divider
42
+ picks pick pick_detail pick_action reason button_ghost choice_footer choice_divider choice_actions
43
43
  ].freeze
44
44
 
45
45
  # Your CSS framework's classes for the engine's screens, by piece, added beside each element's
46
46
  # qube- classes (a String, or an Array of them):
47
- # config.ui_classes = { button: "btn btn-primary", input: "form-control", select: "form-select" }
47
+ # config.ui_classes = { button: "rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white",
48
+ # input: "rounded-md border border-gray-300 px-3 py-2 text-sm" }
48
49
  # A piece not in UI_PIECES raises, naming them.
49
50
  def ui_classes=(map)
50
51
  raise ArgumentError, "ui_classes is a Hash of piece => CSS classes, in #{FILE}" unless map.respond_to?(:each_pair)
@@ -112,6 +112,9 @@ module QubeRails
112
112
  connection.status = status
113
113
  connection.stall_reason = event.stalled? ? event.stall_reason : nil
114
114
  end
115
+ # An upgrade or downgrade in the dashboard shows here.
116
+ type = event.connection.is_a?(Hash) ? event.connection["type"].to_s : ""
117
+ connection.connection_type = type if Connection::TYPES.include?(type)
115
118
  connection.revision = event.revision
116
119
 
117
120
  if event.connected?
@@ -45,6 +45,11 @@ module QubeRails
45
45
  # row stays "starting" and the error is raised: send it again with run.retry_start!, never a
46
46
  # new start, or a run that did start runs twice (two invoices).
47
47
  #
48
+ # Workflows run on realtime connections: on a standard one (connection.standard?) it raises
49
+ # RealtimeRequired before writing a run or calling QuBe Sync. A start QuBe Sync refuses for
50
+ # that (422 realtime_required) is kept as "realtime_required", with the error, and raises
51
+ # RealtimeRequired; once the connection is upgraded, run.retry_start! sends it again.
52
+ #
48
53
  # While record's last run of this operation on connection hasn't ended (completed, failed or
49
54
  # cancelled), it starts nothing new: it returns that run (run.reused? is true), sending its
50
55
  # start again first when QuBe Sync hasn't confirmed it, with the same reference and input. The
@@ -56,6 +61,8 @@ module QubeRails
56
61
  "qube_id): the customer finishes onboarding first"
57
62
  end
58
63
 
64
+ raise_realtime_required(connection) if connection.standard?
65
+
59
66
  run, input_error = claim_run(record, connection)
60
67
  raise input_error if input_error
61
68
  return retry_start(run) if run.reused?
@@ -67,16 +74,29 @@ module QubeRails
67
74
  # the Idempotency-Key, the same workflow, input and webhook URL. QuBe Sync answers a repeat of
68
75
  # a start it took with the run that start made (201, Idempotent-Replayed: true) rather than
69
76
  # starting another, for as long as that run is kept (60 days after it ends); a start it never
70
- # took starts now. Returns the run; a run already answered is returned as it is.
77
+ # took starts now. Returns the run; a run already answered is returned as it is. A start
78
+ # refused as realtime_required is sent again too: QuBe Sync stored nothing for it.
71
79
  def self.retry_start(run)
72
80
  return run if run.qube_run_id
73
- unless run.state == "starting"
74
- raise ArgumentError, "QuBe Sync: run #{run.id} is #{run.state}: only a start that got no answer is sent again"
81
+ unless RETRYABLE_STATES.include?(run.state)
82
+ raise ArgumentError, "QuBe Sync: run #{run.id} is #{run.state}: only a start that got no answer, or " \
83
+ "one refused as realtime_required, is sent again"
75
84
  end
85
+ raise_realtime_required(run.connection) if run.connection.standard?
76
86
 
87
+ run.update_columns(state: "starting", error: nil, updated_at: Time.now) if run.realtime_required?
77
88
  send_start(run, run.input)
78
89
  end
79
90
 
91
+ RETRYABLE_STATES = %w[starting realtime_required].freeze
92
+
93
+ def self.raise_realtime_required(connection)
94
+ raise RealtimeRequired, "QuBe Sync: workflows run on realtime connections, and connection #{connection.id} " \
95
+ "is standard. Upgrade it to realtime from its page in the QuBe Sync dashboard (its " \
96
+ "type can't be changed through the API), then start the run again."
97
+ end
98
+ private_class_method :raise_realtime_required
99
+
80
100
  # The record's run that hasn't ended on connection (reused), or a new row with a new reference
81
101
  # and its input, written together under the connection row's lock: two starts of one record at
82
102
  # once (a double click) find the same row, so they send the same reference and input. Returns
@@ -116,9 +136,11 @@ module QubeRails
116
136
  QubeRails.client.start_run(run.connection.qube_id, self::WORKFLOW, input,
117
137
  reference: run.reference, webhook_url: run.webhook_url)
118
138
  rescue Backend::APIError => e
119
- mark_failed(run) if refused?(e)
120
- raise RealtimeRequired, refusal_detail(e) if refusal_code(e) == "realtime_required"
121
-
139
+ if e.status == 422 && refusal_code(e) == "realtime_required"
140
+ mark_realtime_required(run, refusal_detail(e))
141
+ raise RealtimeRequired, refusal_detail(e)
142
+ end
143
+ mark_failed(run, e) if refused?(e)
122
144
  raise
123
145
  end
124
146
  record_start(run, started.is_a?(Hash) ? started : {})
@@ -155,18 +177,54 @@ module QubeRails
155
177
  end
156
178
  private_class_method :refusal_errors
157
179
 
158
- def self.mark_failed(run)
159
- run.update_columns(state: "failed", updated_at: Time.now)
180
+ # Kept, not failed: QuBe Sync stored nothing, so the same start works once it's upgraded.
181
+ def self.mark_realtime_required(run, detail)
182
+ run.error = { "code" => "realtime_required", "detail" => detail }
183
+ run.state = "realtime_required"
184
+ run.save!
185
+ end
186
+ private_class_method :mark_realtime_required
187
+
188
+ # Failed with QuBe Sync's refusal as its error, so the run status says why.
189
+ def self.mark_failed(run, error)
190
+ refusal = { "code" => "refused", "message" => refusal_message(error),
191
+ "detail" => "QuBe Sync refused the start (#{error.status})." }
192
+ run.update_columns(state: "failed", error: refusal, updated_at: Time.now)
160
193
  end
161
194
  private_class_method :mark_failed
162
195
 
196
+ # A sentence from a refusal's body: {"errors": a sentence, {code, detail}, {field: [messages]}
197
+ # or [{path, message}]}, or {"error": a sentence}.
198
+ def self.refusal_message(error)
199
+ parsed = JSON.parse(error.body.to_s)
200
+ parsed = {} unless parsed.is_a?(Hash)
201
+ text = refusal_text(parsed.key?("errors") ? parsed["errors"] : parsed["error"])
202
+ text.to_s.strip.empty? ? QubeRails.t("status.not_started") : text.strip
203
+ rescue JSON::ParserError
204
+ QubeRails.t("status.not_started")
205
+ end
206
+ private_class_method :refusal_message
207
+
208
+ def self.refusal_text(errors)
209
+ case errors
210
+ when String then errors
211
+ when Array
212
+ errors.map { |e| e.is_a?(Hash) ? [e["path"], e["message"]].compact.join(": ") : e.to_s }.join("; ")
213
+ when Hash
214
+ return errors["detail"] if errors["detail"].is_a?(String)
215
+
216
+ errors.map { |field, messages| "#{field.to_s.tr("_", " ")} #{Array(messages).join(", ")}" }.join("; ")
217
+ end
218
+ end
219
+ private_class_method :refusal_text
220
+
163
221
  # The run's id, links and state from QuBe Sync's answer. Its webhooks may have come first, so
164
222
  # the state is taken only while the row still says "starting".
165
223
  def self.record_start(run, started)
166
224
  links = started["links"].is_a?(Hash) ? started["links"] : {}
167
225
  run.with_lock do
168
226
  run.qube_run_id = started["id"]
169
- run.run_url = links["run"]
227
+ run.run_url = links["self"] || links["run"] # a WorkflowRun's link is self; a webhook's, run
170
228
  run.cancel_url = links["cancel"]
171
229
  run.state = started["state"] if run.state == "starting" && started["state"]
172
230
  run.save!
@@ -296,46 +354,69 @@ module QubeRails
296
354
  { full_name: name }
297
355
  end
298
356
 
299
- # Links each QuickBooks record an ending carries (event.output["references"], keyed by the
300
- # input's path: "customer_ref", "invoice_line_add.0.item_ref") to the record of yours your
301
- # block returns for it, on this run's connection, so the next run refers to it by id. The
302
- # block gets the path and the entry (kind, outcome and record: the record's own list as
303
- # "type", with list_id, edit_sequence and full_name) and returns your record, or nil to skip
304
- # it. An entry with no record (not found, or not reached before a cancel) is skipped. Works on
305
- # an added ending and on a cancelled one, which can carry some. Returns the rows linked.
357
+ # Links the QuickBooks records a run settled to the records of yours your block returns for
358
+ # them, on this run's connection, so the next run refers to them by id (and quickbooks_ref
359
+ # sends { list_id: }). Takes either event that carries them (docs/workflow-record-events.md in
360
+ # QuBe Sync):
361
+ # - a "records" notification, sent as each pass settles them: event.data["records"], each
362
+ # with paths, action (picked, created, ...), kind, sent and record;
363
+ # - an ending: event.output["refs"], { path => { list_id, type } } for every reference.
364
+ # The block gets the input's path ("customer_ref", "invoice_line_add.0.item_ref") and the
365
+ # entry (list_id, type, and from a notification also kind, action, full_name, edit_sequence,
366
+ # sent), and returns your record, or nil to skip it. Returns the rows linked.
306
367
  # link_references(event) do |path, entry|
307
368
  # record.customer if path == "customer_ref"
308
369
  # end
309
370
  def link_references(event)
371
+ self.class.linkable(event).each_with_object([]) do |(path, entry), linked|
372
+ app_record = yield(path, entry)
373
+ next unless app_record
374
+
375
+ kind = entry["type"].to_s.empty? ? entry["kind"] : entry["type"]
376
+ linked << connection.link(app_record, kind: kind, qb_id: entry["list_id"],
377
+ edit_sequence: entry["edit_sequence"], name: entry["full_name"])
378
+ end
379
+ end
380
+
381
+ # The [path, entry] pairs link_references links, from a "records" notification or an ending.
382
+ def self.linkable(event)
383
+ records = event["name"] == "records" && event["data"].is_a?(Hash) ? event["data"]["records"] : nil
384
+ return linkable_records(records) if records.is_a?(Array)
385
+
310
386
  output = event["output"]
311
- references = output.is_a?(Hash) ? output["references"] : nil
312
- return [] unless references.is_a?(Hash)
387
+ refs = output.is_a?(Hash) ? output["refs"] : nil
388
+ return [] unless refs.is_a?(Hash)
313
389
 
314
- references.each_with_object([]) do |(path, entry), linked|
315
- next unless entry.is_a?(Hash) && entry["record"].is_a?(Hash)
390
+ refs.filter_map do |path, entry|
391
+ next unless entry.is_a?(Hash) && !entry["list_id"].to_s.empty?
316
392
 
317
- found = entry["record"]
318
- next if found["list_id"].to_s.empty?
393
+ [path, { "list_id" => entry["list_id"], "type" => entry["type"] }]
394
+ end
395
+ end
319
396
 
320
- app_record = yield(path, entry)
321
- next unless app_record
397
+ def self.linkable_records(records)
398
+ records.flat_map do |entry|
399
+ found = entry.is_a?(Hash) ? entry["record"] : nil
400
+ next [] unless found.is_a?(Hash) && !found["list_id"].to_s.empty?
322
401
 
323
- kind = found["type"].to_s.empty? ? entry["kind"] : found["type"]
324
- linked << connection.link(app_record, kind: kind, qb_id: found["list_id"],
325
- edit_sequence: found["edit_sequence"], name: found["full_name"])
402
+ shown = found.slice("list_id", "type", "full_name", "edit_sequence")
403
+ .merge(entry.slice("kind", "action", "sent"))
404
+ Array(entry["paths"]).map { |path| [path, shown] }
326
405
  end
327
406
  end
328
407
 
329
408
  # After your user's choice is in: the question is forgotten, unless the run has asked another
330
- # since (its token is the question's own). taken: QuBe Sync took the answer, so the run is
331
- # running again until its next webhook (which waits on the Web Connector's next poll).
332
- def answered(token, taken: false)
409
+ # since (its token is the question's own). taken: the run has moved past the question (QuBe
410
+ # Sync took this answer, or said it was answered or asked again), so it reads as running until
411
+ # its next webhook (which waits on the Web Connector's next poll). cancelling: the answer was
412
+ # its cancel, so it reads "Cancelling…" (state "cancelling", this engine's own) until then.
413
+ def answered(token, taken: false, cancelling: false)
333
414
  run.with_lock do
334
415
  question = run.open_question
335
416
  if question && question["token"] == token
336
417
  run.question = nil
337
418
  run.links = nil
338
- run.state = "running" if taken
419
+ run.state = cancelling ? "cancelling" : "running" if taken
339
420
  run.save!
340
421
  end
341
422
  end
@@ -364,10 +445,12 @@ module QubeRails
364
445
  # whatever the handler does: state, outcome, and a failure's error or a cancel's reason.
365
446
  run.state = event.run_state || run_state_for(event)
366
447
  run.outcome = event.outcome
448
+ run.headline = event["headline"] if event["headline"].is_a?(String)
367
449
  if ended?(event)
368
450
  run.ended_at ||= Time.now
369
- run.error = event.error if event.failed?
451
+ run.error = event["error"] if event.failed? # raw: qube_sync 0.6 types event.error
370
452
  run.cancel_reason = event.cancel_reason if event.cancelled?
453
+ run.cancel_url = nil # links.cancel works only until the run ends
371
454
  end
372
455
 
373
456
  if event.awaiting_input?