agreement_engine 0.1.0 → 0.2.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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +17 -0
  3. data/.ruby-version +1 -1
  4. data/CHANGELOG.md +36 -0
  5. data/README.md +278 -17
  6. data/app/controllers/agreement_engine/admin/documents_controller.rb +6 -32
  7. data/app/controllers/agreement_engine/admin/issues_controller.rb +50 -0
  8. data/app/controllers/agreement_engine/agreements_controller.rb +5 -5
  9. data/app/controllers/agreement_engine/consents_controller.rb +47 -0
  10. data/app/controllers/agreement_engine/documents_controller.rb +4 -7
  11. data/app/controllers/agreement_engine/receipts_controller.rb +31 -0
  12. data/app/controllers/agreement_engine/record_documents_controller.rb +47 -0
  13. data/app/controllers/agreement_engine/signatures_controller.rb +89 -0
  14. data/app/controllers/agreement_engine/verifications_controller.rb +18 -0
  15. data/app/mailers/agreement_engine/receipt_mailer.rb +18 -0
  16. data/app/models/agreement_engine/acceptance.rb +84 -0
  17. data/app/models/agreement_engine/consent_withdrawal.rb +13 -0
  18. data/app/models/agreement_engine/document.rb +81 -3
  19. data/app/views/agreement_engine/admin/documents/index.html.erb +1 -2
  20. data/app/views/agreement_engine/admin/documents/show.html.erb +52 -2
  21. data/app/views/agreement_engine/admin/issues/new.html.erb +51 -0
  22. data/app/views/agreement_engine/agreements/show.html.erb +4 -1
  23. data/app/views/agreement_engine/consents/show.html.erb +19 -0
  24. data/app/views/agreement_engine/documents/_issued_version.html.erb +5 -0
  25. data/app/views/agreement_engine/documents/{terms.html.erb → show.html.erb} +4 -4
  26. data/app/views/agreement_engine/receipt_mailer/copy.text.erb +5 -0
  27. data/app/views/agreement_engine/signatures/show.html.erb +37 -0
  28. data/app/views/agreement_engine/verifications/show.html.erb +22 -0
  29. data/config/locales/en.yml +44 -0
  30. data/config/routes.rb +12 -3
  31. data/db/migrate/20261120011146_add_issued_versions_to_agreement_engine_documents.rb +8 -0
  32. data/db/migrate/20261120022247_create_agreement_engine_acceptances.rb +22 -0
  33. data/db/migrate/20261120023407_create_agreement_engine_consent_withdrawals.rb +12 -0
  34. data/db/migrate/20261120024007_add_signature_fields_to_agreement_engine_acceptances.rb +7 -0
  35. data/db/migrate/20261120030101_add_subject_to_agreement_engine_documents.rb +9 -0
  36. data/db/migrate/20261120041730_add_carry_over_to_agreement_engine_acceptances.rb +8 -0
  37. data/db/migrate/20261120141925_add_period_to_agreement_engine_acceptances.rb +6 -0
  38. data/db/migrate/20261120143946_add_database_guards_to_agreement_engine.rb +9 -0
  39. data/db/migrate/20261120145611_add_one_signature_index_to_agreement_engine_acceptances.rb +5 -0
  40. data/docs/byte-form/examples/blank-standing/bytes.json +1 -0
  41. data/docs/byte-form/examples/blank-standing/input.json +15 -0
  42. data/docs/byte-form/examples/blank-standing/sha256 +1 -0
  43. data/docs/byte-form/examples/with-values/bytes.json +1 -0
  44. data/docs/byte-form/examples/with-values/input.json +15 -0
  45. data/docs/byte-form/examples/with-values/sha256 +1 -0
  46. data/docs/byte-form.md +44 -0
  47. data/exe/agreement_engine-verify +14 -0
  48. data/lib/agreement_engine/acceptance_event.rb +22 -0
  49. data/lib/agreement_engine/byte_form.rb +28 -0
  50. data/lib/agreement_engine/configuration.rb +35 -2
  51. data/lib/agreement_engine/consent.rb +26 -0
  52. data/lib/agreement_engine/database_guards.rb +46 -0
  53. data/lib/agreement_engine/document_type.rb +23 -0
  54. data/lib/agreement_engine/enforceable.rb +6 -7
  55. data/lib/agreement_engine/engine.rb +7 -0
  56. data/lib/agreement_engine/html_to_page.rb +63 -0
  57. data/lib/agreement_engine/integrity.rb +23 -0
  58. data/lib/agreement_engine/pages_elements.rb +29 -0
  59. data/lib/agreement_engine/period.rb +23 -0
  60. data/lib/agreement_engine/receipt.rb +43 -0
  61. data/lib/agreement_engine/seed.rb +37 -0
  62. data/lib/agreement_engine/signable.rb +25 -9
  63. data/lib/agreement_engine/upgrade.rb +75 -0
  64. data/lib/agreement_engine/verification.rb +13 -0
  65. data/lib/agreement_engine/version.rb +1 -1
  66. data/lib/agreement_engine.rb +43 -1
  67. data/lib/generators/agreement_engine/templates/initializer.rb +5 -4
  68. data/lib/tasks/agreement_engine.rake +18 -15
  69. metadata +64 -9
  70. data/app/views/agreement_engine/admin/documents/_form.html.erb +0 -44
  71. data/app/views/agreement_engine/admin/documents/edit.html.erb +0 -5
  72. data/app/views/agreement_engine/admin/documents/new.html.erb +0 -5
  73. data/app/views/agreement_engine/documents/privacy.html.erb +0 -16
  74. data/lib/agreement_engine/agreement.rb +0 -23
@@ -9,3 +9,47 @@ en:
9
9
  decline: "I Decline"
10
10
  destroy:
11
11
  declined: "To continue using the service, please sign in and accept the %{agreement}."
12
+ consents:
13
+ show:
14
+ statement: "I have read this disclosure, I can open and keep records as it describes, and I agree to receive and sign records electronically."
15
+ consent: "I Consent"
16
+ held: "You have consented to electronic records. You can withdraw that consent here."
17
+ withdraw: "Withdraw"
18
+ create:
19
+ given: "Your consent to electronic records is recorded."
20
+ destroy:
21
+ withdrawn: "Your consent to electronic records is withdrawn."
22
+ signatures:
23
+ show:
24
+ statement: "By typing your full name and selecting Sign, you sign the %{document} above electronically, and your electronic signature has the same effect as a handwritten one."
25
+ typed_name: "Your full name"
26
+ sign: "Sign"
27
+ update:
28
+ blank: "Type your full name to sign."
29
+ stale: "This document changed while you were reading it. Read the current version below and sign again."
30
+ signed: "You signed the %{document}."
31
+ record_documents:
32
+ show:
33
+ statement: "By selecting I Accept, you agree to the %{document} above."
34
+ accept: "I Accept"
35
+ update:
36
+ accepted: "You accepted the %{document}."
37
+ receipt_mailer:
38
+ copy:
39
+ subject: "Your copy of the %{document}"
40
+ body: "Attached are your copy of the %{document} and the byte-form file its SHA-256 hash was taken from. Running any SHA-256 tool on that file prints the hash below."
41
+ verifications:
42
+ show:
43
+ title: "Check a signed copy"
44
+ description: "Choose the byte-form file from your copy and enter the SHA-256 hash it shows. Nothing you send is stored."
45
+ file: "Byte-form file"
46
+ hash: "SHA-256 hash"
47
+ check: "Check"
48
+ matched: "The file matches this hash."
49
+ not_matched: "The file does not match this hash."
50
+ documents:
51
+ show:
52
+ none:
53
+ default: "Nothing has been published here yet."
54
+ terms_of_service: "No terms of service have been published yet."
55
+ privacy_policy: "No privacy policy has been published yet."
data/config/routes.rb CHANGED
@@ -1,10 +1,19 @@
1
1
  AgreementEngine::Engine.routes.draw do
2
2
  resources :agreements, only: [:show, :update, :destroy]
3
+ resource :consent, only: [:show, :create, :destroy]
4
+ resource :verification, only: [:show, :create], path: "verify"
5
+ resources :signatures, only: [:show, :update], param: :document_type
6
+ resources :record_documents, only: [:show, :update], param: :code, path: "records"
7
+ resources :receipts, only: [:show] do
8
+ get :byte_form, on: :member
9
+ end
3
10
 
4
- get "terms", to: "documents#terms", as: :terms
5
- get "privacy", to: "documents#privacy", as: :privacy
11
+ get "terms", to: "documents#show", defaults: {document_type: "terms_of_service"}, as: :terms
12
+ get "privacy", to: "documents#show", defaults: {document_type: "privacy_policy"}, as: :privacy
13
+ get "documents/:document_type", to: "documents#show", as: :public_document
6
14
 
7
15
  namespace :admin do
8
- resources :documents
16
+ resources :documents, only: [:index, :show, :destroy]
17
+ resources :issues, only: [:new, :create]
9
18
  end
10
19
  end
@@ -0,0 +1,8 @@
1
+ class AddIssuedVersionsToAgreementEngineDocuments < ActiveRecord::Migration[8.0]
2
+ def change
3
+ add_reference :agreement_engine_documents, :page_version, foreign_key: {to_table: :keystone_ui_pages_versions, on_delete: :nullify}
4
+ add_column :agreement_engine_documents, :frozen_copy, :json
5
+ add_column :agreement_engine_documents, :content_hash, :string
6
+ add_column :agreement_engine_documents, :byte_form_version, :integer
7
+ end
8
+ end
@@ -0,0 +1,22 @@
1
+ class CreateAgreementEngineAcceptances < ActiveRecord::Migration[8.0]
2
+ def change
3
+ create_table :agreement_engine_acceptances do |t|
4
+ t.references :signer, polymorphic: true, null: false
5
+ t.references :document, null: false, foreign_key: {to_table: :agreement_engine_documents}
6
+ t.string :content_hash
7
+ t.integer :byte_form_version
8
+ t.datetime :accepted_at, null: false
9
+ t.string :ip_address
10
+ t.text :user_agent
11
+ t.text :statement
12
+ t.string :button_text
13
+ t.json :person
14
+ t.json :account
15
+ t.json :sign_in
16
+ t.string :engine_version
17
+ t.string :pages_version
18
+
19
+ t.timestamps
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,12 @@
1
+ class CreateAgreementEngineConsentWithdrawals < ActiveRecord::Migration[8.0]
2
+ def change
3
+ create_table :agreement_engine_consent_withdrawals do |t|
4
+ t.references :acceptance, null: false, index: {unique: true}, foreign_key: {to_table: :agreement_engine_acceptances}
5
+ t.datetime :withdrawn_at, null: false
6
+ t.string :ip_address
7
+ t.text :user_agent
8
+
9
+ t.timestamps
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,7 @@
1
+ class AddSignatureFieldsToAgreementEngineAcceptances < ActiveRecord::Migration[8.0]
2
+ def change
3
+ add_column :agreement_engine_acceptances, :strength, :string, null: false, default: "click_accept"
4
+ add_column :agreement_engine_acceptances, :typed_name, :string
5
+ add_reference :agreement_engine_acceptances, :consent, foreign_key: {to_table: :agreement_engine_acceptances}
6
+ end
7
+ end
@@ -0,0 +1,9 @@
1
+ class AddSubjectToAgreementEngineDocuments < ActiveRecord::Migration[8.0]
2
+ def change
3
+ add_reference :agreement_engine_documents, :subject, polymorphic: true
4
+ add_column :agreement_engine_documents, :code, :string
5
+ add_index :agreement_engine_documents, :code, unique: true
6
+ remove_index :agreement_engine_documents, [:document_type, :version], unique: true
7
+ add_index :agreement_engine_documents, [:document_type, :subject_type, :subject_id, :version], unique: true, name: "index_agreement_engine_documents_on_type_subject_and_version"
8
+ end
9
+ end
@@ -0,0 +1,8 @@
1
+ class AddCarryOverToAgreementEngineAcceptances < ActiveRecord::Migration[8.0]
2
+ def change
3
+ change_column_null :agreement_engine_acceptances, :accepted_at, true
4
+ add_column :agreement_engine_acceptances, :carried_over, :boolean, null: false, default: false
5
+ add_column :agreement_engine_acceptances, :time_reported_by_host, :boolean, null: false, default: false
6
+ add_column :agreement_engine_acceptances, :snapshot_taken_at, :datetime
7
+ end
8
+ end
@@ -0,0 +1,6 @@
1
+ class AddPeriodToAgreementEngineAcceptances < ActiveRecord::Migration[8.0]
2
+ def change
3
+ add_column :agreement_engine_acceptances, :period_starts_on, :date
4
+ add_column :agreement_engine_acceptances, :period_ends_on, :date
5
+ end
6
+ end
@@ -0,0 +1,9 @@
1
+ class AddDatabaseGuardsToAgreementEngine < ActiveRecord::Migration[8.0]
2
+ def up
3
+ execute AgreementEngine::DatabaseGuards::INSTALL if connection.adapter_name.match?(/postg/i)
4
+ end
5
+
6
+ def down
7
+ execute AgreementEngine::DatabaseGuards::UNINSTALL if connection.adapter_name.match?(/postg/i)
8
+ end
9
+ end
@@ -0,0 +1,5 @@
1
+ class AddOneSignatureIndexToAgreementEngineAcceptances < ActiveRecord::Migration[8.0]
2
+ def change
3
+ add_index :agreement_engine_acceptances, [:signer_type, :signer_id, :document_id], unique: true, where: "strength = 'signature'", name: "index_agreement_engine_acceptances_one_signature"
4
+ end
5
+ end
@@ -0,0 +1 @@
1
+ {"document":{"schema_version":1,"sections":[{"id":"s1","rows":[{"columns":[{"elements":[{"fields":{"text":"Terms of Service"},"id":"e1","key":"heading"},{"fields":{"text":{"html":"<p>Be <strong>kind</strong>.</p>"}},"id":"e2","key":"paragraph"}],"id":"c1"}],"id":"r1"}]}]},"number":1,"period":null,"slug":"terms","values":{}}
@@ -0,0 +1,15 @@
1
+ {
2
+ "slug": "terms",
3
+ "number": 1,
4
+ "document": {
5
+ "schema_version": 1,
6
+ "sections": [
7
+ {"id": "s1", "rows": [{"id": "r1", "columns": [{"id": "c1", "elements": [
8
+ {"id": "e1", "key": "heading", "fields": {"text": "Terms of Service"}},
9
+ {"id": "e2", "key": "paragraph", "fields": {"text": {"html": "<p>Be <strong>kind</strong>.</p>"}}}
10
+ ]}]}]}
11
+ ]
12
+ },
13
+ "values": {},
14
+ "period": null
15
+ }
@@ -0,0 +1 @@
1
+ f4cec5ec9cbb78f7955742ac2afaca791411b03ce16fb0bc00237abf942473c7
@@ -0,0 +1 @@
1
+ {"document":{"schema_version":1,"sections":[{"id":"s1","rows":[{"columns":[{"elements":[{"fields":{"text":{"fallback":"Client","value":"client_name"}},"id":"e1","key":"heading"},{"fields":{"items":[{"text":"Demo one"},{"text":"Demo two"}],"style":"numbered"},"id":"e2","key":"legal_list"}],"id":"c1"}],"id":"r1"}]}]},"number":3,"period":null,"slug":"plan-sign-off","values":{"client_name":"Acme Co","demo_count":2}}
@@ -0,0 +1,15 @@
1
+ {
2
+ "slug": "plan-sign-off",
3
+ "number": 3,
4
+ "document": {
5
+ "schema_version": 1,
6
+ "sections": [
7
+ {"id": "s1", "rows": [{"id": "r1", "columns": [{"id": "c1", "elements": [
8
+ {"id": "e1", "key": "heading", "fields": {"text": {"value": "client_name", "fallback": "Client"}}},
9
+ {"id": "e2", "key": "legal_list", "fields": {"style": "numbered", "items": [{"text": "Demo one"}, {"text": "Demo two"}]}}
10
+ ]}]}]}
11
+ ]
12
+ },
13
+ "values": {"client_name": "Acme Co", "demo_count": 2},
14
+ "period": null
15
+ }
@@ -0,0 +1 @@
1
+ 4873c8844f7067aaeb3e45382c3702fec824899619a1cf9feda70ad2aaf58dac
data/docs/byte-form.md ADDED
@@ -0,0 +1,44 @@
1
+ # The byte form, version 1
2
+
3
+ Every issued version in agreement_engine carries a SHA-256 hash. The hash is
4
+ taken from the version's byte form, a fixed series of bytes built from its
5
+ content by the rule below. Anyone holding a byte-form file can recompute the
6
+ hash with any SHA-256 tool and compare it with the hash recorded on a
7
+ signature, without trusting the app that recorded it.
8
+
9
+ ## The rule
10
+
11
+ 1. Build one JSON object with exactly five keys:
12
+ - `slug`: the slug of the keystone_ui-pages page the version was issued from.
13
+ - `number`: that page version's number, as an integer.
14
+ - `document`: that page version's JSON document, exactly as it was published.
15
+ - `values`: the host values the document was filled with, as an object, or
16
+ `{}` when there are none.
17
+ - `period`: the period the document covers, or `null` when it has none.
18
+ 2. Sort the keys of every object, at every depth, by their characters in
19
+ Unicode code point order. Arrays keep their order.
20
+ 3. Write the object as JSON with no whitespace between tokens, encoded as
21
+ UTF-8. Characters outside ASCII are written as themselves, not escaped.
22
+ 4. The hash is the SHA-256 of those bytes, written as 64 lowercase hex digits.
23
+
24
+ Rendered HTML and PDFs are never part of the bytes, so a change to how a page
25
+ is drawn never changes a hash. Version 1 of the rule never changes. A later
26
+ rule would be version 2, kept beside version 1 for as long as any version 1
27
+ hash exists, and each issued version records which version it was hashed with.
28
+
29
+ ## Checking a file
30
+
31
+ ```
32
+ shasum -a 256 copy.json
33
+ agreement_engine-verify copy.json <hash>
34
+ ```
35
+
36
+ The `agreement_engine-verify` command is installed with the gem and loads no
37
+ app. The verify page at `/verify` gives the same answer.
38
+
39
+ ## Worked examples
40
+
41
+ Each folder under `docs/byte-form/examples/` holds an `input.json` written for
42
+ reading, the `bytes.json` the rule produces from it, and the `sha256` of those
43
+ bytes. The gem's test suite fails if any example would produce different bytes
44
+ or a different hash.
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative "../lib/agreement_engine/verification"
5
+
6
+ file, hash_value = ARGV
7
+ abort "Usage: agreement_engine-verify <byte-form file> <sha-256 hash>" unless file && hash_value
8
+
9
+ if AgreementEngine::Verification.matches?(File.binread(file), hash_value)
10
+ puts "The file matches this hash."
11
+ else
12
+ puts "The file does not match this hash."
13
+ exit 1
14
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgreementEngine
4
+ AcceptanceEvent = Data.define(:acceptance, :first_signature) do
5
+ def self.for(acceptance)
6
+ new(acceptance: acceptance, first_signature: first_signature?(acceptance))
7
+ end
8
+
9
+ def self.first_signature?(acceptance)
10
+ acceptance.strength == "signature" && acceptance.document.subject_id.present? &&
11
+ !acceptance.document.acceptances.where(strength: "signature").where.not(id: acceptance.id).exists?
12
+ end
13
+
14
+ def document = acceptance.document
15
+ def document_type = document.document_type.to_sym
16
+ def person = acceptance.person
17
+ def account = acceptance.account
18
+ def strength = acceptance.strength.to_sym
19
+ def subject = document.subject
20
+ def first_signature? = first_signature
21
+ end
22
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "json"
5
+
6
+ module AgreementEngine
7
+ module ByteForm
8
+ VERSION = 1
9
+
10
+ module_function
11
+
12
+ def encode(slug:, number:, document:, values: {}, period: nil)
13
+ JSON.generate(sorted({"slug" => slug, "number" => number, "document" => document, "values" => values, "period" => period}))
14
+ end
15
+
16
+ def digest(**content)
17
+ Digest::SHA256.hexdigest(encode(**content))
18
+ end
19
+
20
+ def sorted(value)
21
+ case value
22
+ when Hash then value.sort_by { |key, _| key.to_s }.to_h { |key, nested| [key.to_s, sorted(nested)] }
23
+ when Array then value.map { |nested| sorted(nested) }
24
+ else value
25
+ end
26
+ end
27
+ end
28
+ end
@@ -2,15 +2,24 @@
2
2
 
3
3
  module AgreementEngine
4
4
  class Configuration
5
- attr_accessor :agreements
5
+ attr_accessor :document_types
6
6
  attr_accessor :current_user_method
7
7
  attr_accessor :signed_in_method
8
8
  attr_accessor :auth_controller_method
9
9
  attr_accessor :sign_out_method
10
10
  attr_accessor :admin_auth_method
11
+ attr_accessor :evidence_method
12
+ attr_accessor :electronic_consent
13
+ attr_accessor :values_method
14
+ attr_accessor :may_sign_method
15
+ attr_accessor :return_check_method
16
+ attr_accessor :acceptance_handler
17
+ attr_accessor :copy_email_types
18
+ attr_accessor :mailer_from
11
19
 
12
20
  def initialize
13
- @agreements = []
21
+ @document_types = []
22
+ @copy_email_types = []
14
23
 
15
24
  @current_user_method = ->(c) { c.current_user }
16
25
  @signed_in_method = ->(c) { c.user_signed_in? }
@@ -27,6 +36,30 @@ module AgreementEngine
27
36
  }
28
37
  end
29
38
 
39
+ def agreements=(_list)
40
+ raise ArgumentError, "config.agreements was replaced by config.document_types in agreement_engine 0.2. Register each agreement as AgreementEngine::DocumentType.new(key:, title:, kind: :standing, strength: :click_accept, prompts: true)."
41
+ end
42
+
43
+ def registered_document_types
44
+ document_types + (electronic_consent ? [Consent::TYPE] : [])
45
+ end
46
+
47
+ def evidence(controller, signer)
48
+ (evidence_method&.call(controller, signer) || {}).to_h.transform_keys(&:to_sym)
49
+ end
50
+
51
+ def allowed_return_path(path)
52
+ path = path.to_s
53
+ return unless path.start_with?("/") && !path.start_with?("//") && !path.include?("\\")
54
+ return if return_check_method && return_check_method.call(path) != true
55
+
56
+ path
57
+ end
58
+
59
+ def may_sign?(controller, person, document)
60
+ may_sign_method.present? && may_sign_method.call(controller, person, document) == true
61
+ end
62
+
30
63
  def current_user(controller) = current_user_method.call(controller)
31
64
  def signed_in?(controller) = signed_in_method.call(controller)
32
65
  def auth_controller?(controller) = auth_controller_method.call(controller)
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+
5
+ module AgreementEngine
6
+ module Consent
7
+ TYPE = DocumentType.new(key: :electronic_records_consent, title: "Consent to Electronic Records", kind: :standing, strength: :click_accept)
8
+
9
+ STARTING_TEXT = [
10
+ [:heading, "Consent to Electronic Records"],
11
+ [:paragraph, "We would like to give you agreements, notices and other records electronically, and to have you sign them electronically. Please read this before you agree."],
12
+ [:heading, "Paper copies"],
13
+ [:paragraph, "You may ask for a paper copy of any record we give you electronically by contacting us. We will tell you of any fee before we send it."],
14
+ [:heading, "Withdrawing your consent"],
15
+ [:paragraph, "You may withdraw this consent at any time from your account. Withdrawing does not change records you have already signed. After you withdraw, we will tell you how we will give you records from then on."],
16
+ [:heading, "What you need to open and keep records"],
17
+ [:paragraph, "You need a device with a current web browser, an internet connection, a program that opens PDF files and an email address. You can keep a record by downloading or printing it. If these needs change, we will tell you and ask for your consent again."]
18
+ ].freeze
19
+
20
+ module_function
21
+
22
+ def seed!
23
+ Seed.issue_starting_version(TYPE, STARTING_TEXT)
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgreementEngine
4
+ module DatabaseGuards
5
+ INSTALL = <<~SQL
6
+ CREATE OR REPLACE FUNCTION agreement_engine_refuse_acceptance_change() RETURNS trigger AS $$
7
+ BEGIN
8
+ RAISE EXCEPTION 'agreement_engine acceptances cannot be changed or deleted';
9
+ END;
10
+ $$ LANGUAGE plpgsql;
11
+
12
+ CREATE OR REPLACE FUNCTION agreement_engine_refuse_issued_change() RETURNS trigger AS $$
13
+ BEGIN
14
+ IF OLD.content_hash IS NULL THEN
15
+ IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
16
+ RETURN NEW;
17
+ END IF;
18
+ IF TG_OP = 'DELETE' THEN
19
+ RAISE EXCEPTION 'agreement_engine issued versions cannot be deleted';
20
+ END IF;
21
+ IF NEW.frozen_copy::text IS DISTINCT FROM OLD.frozen_copy::text
22
+ OR NEW.content_hash IS DISTINCT FROM OLD.content_hash
23
+ OR NEW.effective_at IS DISTINCT FROM OLD.effective_at THEN
24
+ RAISE EXCEPTION 'agreement_engine issued versions cannot be changed';
25
+ END IF;
26
+ RETURN NEW;
27
+ END;
28
+ $$ LANGUAGE plpgsql;
29
+
30
+ DROP TRIGGER IF EXISTS agreement_engine_acceptances_frozen ON agreement_engine_acceptances;
31
+ CREATE TRIGGER agreement_engine_acceptances_frozen BEFORE UPDATE OR DELETE ON agreement_engine_acceptances
32
+ FOR EACH ROW EXECUTE FUNCTION agreement_engine_refuse_acceptance_change();
33
+
34
+ DROP TRIGGER IF EXISTS agreement_engine_documents_frozen ON agreement_engine_documents;
35
+ CREATE TRIGGER agreement_engine_documents_frozen BEFORE UPDATE OR DELETE ON agreement_engine_documents
36
+ FOR EACH ROW EXECUTE FUNCTION agreement_engine_refuse_issued_change();
37
+ SQL
38
+
39
+ UNINSTALL = <<~SQL
40
+ DROP TRIGGER IF EXISTS agreement_engine_acceptances_frozen ON agreement_engine_acceptances;
41
+ DROP TRIGGER IF EXISTS agreement_engine_documents_frozen ON agreement_engine_documents;
42
+ DROP FUNCTION IF EXISTS agreement_engine_refuse_acceptance_change();
43
+ DROP FUNCTION IF EXISTS agreement_engine_refuse_issued_change();
44
+ SQL
45
+ end
46
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgreementEngine
4
+ DocumentType = Data.define(:key, :title, :kind, :strength, :template, :prompts) do
5
+ def initialize(key:, title:, kind:, strength:, template: nil, prompts: false)
6
+ super
7
+ end
8
+
9
+ def signature?
10
+ strength.to_sym == :signature
11
+ end
12
+
13
+ def per_record?
14
+ kind.to_sym == :per_record
15
+ end
16
+
17
+ def standing?
18
+ !per_record?
19
+ end
20
+
21
+ def to_param = key.to_s
22
+ end
23
+ end
@@ -10,13 +10,12 @@ module AgreementEngine
10
10
  end
11
11
 
12
12
  def require_accepted_agreements!
13
- AgreementEngine.config.agreements.select(&:prompt_when_updated).each do |agreement|
14
- if agreement.not_accepted_by?(AgreementEngine.config.current_user(self))
15
- store_location_for(:user, request.fullpath) unless request.fullpath.start_with?("/agreements/")
16
- redirect_to agreement_engine.agreement_path(agreement)
17
- break
18
- end
19
- end
13
+ person = AgreementEngine.config.current_user(self)
14
+ type = AgreementEngine.config.registered_document_types.find { |candidate| candidate.standing? && candidate.prompts && !person.accepted_current?(candidate.key) }
15
+ return unless type
16
+
17
+ store_location_for(:user, request.fullpath) unless request.fullpath.start_with?("/agreements/")
18
+ redirect_to agreement_engine.agreement_path(type)
20
19
  end
21
20
  end
22
21
  end
@@ -1,9 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "pages_elements"
4
+
3
5
  module AgreementEngine
4
6
  class Engine < ::Rails::Engine
5
7
  isolate_namespace AgreementEngine
6
8
 
9
+ initializer "agreement_engine.pages_elements" do
10
+ AgreementEngine::PagesElements.register(KeystoneUi::Pages.catalog)
11
+ ActiveSupport.on_load(:action_view) { include AgreementEngine::PagesElements::Drawing }
12
+ end
13
+
7
14
  initializer "agreement_engine.url_helpers" do
8
15
  ActiveSupport.on_load(:action_controller) do
9
16
  helper Rails.application.routes.url_helpers
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "nokogiri"
4
+ require "securerandom"
5
+
6
+ module AgreementEngine
7
+ module HtmlToPage
8
+ Result = Data.define(:document, :left_out)
9
+
10
+ HEADINGS = %w[h1 h2 h3 h4 h5 h6].freeze
11
+ HEADING_SIZES = {"h1" => "lg", "h2" => "md"}.freeze
12
+ PARAGRAPHS = %w[p div].freeze
13
+ LISTS = {"ul" => "bulleted", "ol" => "numbered"}.freeze
14
+ INLINE_TAGS = %w[a strong b em i br].freeze
15
+
16
+ module_function
17
+
18
+ def convert(html)
19
+ elements = []
20
+ left_out = []
21
+ blocks(Nokogiri::HTML5.fragment(html.to_s)).each do |node|
22
+ element = element_for(node)
23
+ element ? elements << element : left_out << node.name
24
+ end
25
+ document = KeystoneUi::Pages::Document.blank
26
+ document["sections"][0]["rows"][0]["columns"][0]["elements"] = elements
27
+ Result.new(document: document, left_out: left_out.uniq)
28
+ end
29
+
30
+ def blocks(fragment)
31
+ fragment.children.flat_map do |node|
32
+ next [] if node.text? && node.text.strip.empty?
33
+ next blocks(node) if node.name == "div" && node["class"].to_s.include?("trix-content")
34
+
35
+ [node]
36
+ end
37
+ end
38
+
39
+ def element_for(node)
40
+ return paragraph(node.to_html) if node.text?
41
+ return heading(node) if HEADINGS.include?(node.name)
42
+ return paragraph(node.inner_html) if PARAGRAPHS.include?(node.name) && node.css("img, table, figure, action-text-attachment").empty?
43
+ list(node) if LISTS.key?(node.name)
44
+ end
45
+
46
+ def heading(node)
47
+ element("heading", "text" => node.text.strip, "size" => HEADING_SIZES.fetch(node.name, "sm"))
48
+ end
49
+
50
+ def paragraph(inner_html)
51
+ kept = Rails::HTML5::SafeListSanitizer.new.sanitize(inner_html, tags: INLINE_TAGS, attributes: %w[href])
52
+ element("paragraph", "text" => {"html" => "<p>#{kept}</p>"})
53
+ end
54
+
55
+ def list(node)
56
+ element("legal_list", "style" => LISTS.fetch(node.name), "items" => node.css("> li").map { |item| {"text" => item.text.strip} })
57
+ end
58
+
59
+ def element(key, fields)
60
+ {"id" => SecureRandom.uuid, "key" => key, "fields" => fields}
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgreementEngine
4
+ module Integrity
5
+ module_function
6
+
7
+ def problems
8
+ document_problems + acceptance_problems
9
+ end
10
+
11
+ def document_problems
12
+ Document.where.not(content_hash: nil).find_each.reject(&:hash_intact?).map do |document|
13
+ "Document #{document.code}: the frozen copy no longer produces its hash"
14
+ end
15
+ end
16
+
17
+ def acceptance_problems
18
+ Acceptance.includes(:document).where.not(content_hash: nil).find_each.select { |acceptance| acceptance.content_hash != acceptance.document.content_hash }.map do |acceptance|
19
+ "Acceptance #{acceptance.id}: its hash differs from document #{acceptance.document.code}"
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AgreementEngine
4
+ module PagesElements
5
+ module_function
6
+
7
+ def register(catalog)
8
+ catalog.register(key: :legal_list, name: "List", component: :agreement_engine_legal_list, icon: :text, group: "Text", pdf: method(:pdf_list),
9
+ fields: [{key: :style, label: "Style", kind: :one_of, options: %w[bulleted numbered], default: "bulleted"},
10
+ {key: :items, label: "Items", kind: :list, entry: [{key: :text, label: "Text", kind: :long_text}],
11
+ default: [{"text" => "First item"}, {"text" => "Second item"}]}])
12
+ end
13
+
14
+ def pdf_list(surface, fields)
15
+ Array(fields[:items]).each_with_index do |item, index|
16
+ marker = fields[:style].to_s == "numbered" ? "#{index + 1}." : "\u2022"
17
+ surface.text("#{marker} #{item.to_h.stringify_keys["text"]}", size: "--text-base", font: "--ks-font-body", color: "--ks-color-text", leading: "--leading-relaxed")
18
+ end
19
+ end
20
+
21
+ module Drawing
22
+ def agreement_engine_legal_list(style:, items:)
23
+ tag.public_send(style == :numbered ? :ol : :ul, class: style == :numbered ? "list-decimal pl-6" : "list-disc pl-6") do
24
+ safe_join(items.map { |item| tag.li(item[:text]) })
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end