lunixi-sdk 1.2.2 → 2.0.2

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 (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +62 -0
  3. data/README.md +278 -10
  4. data/README.tr.md +282 -8
  5. data/docs/ruby.en.md +11 -1
  6. data/docs/ruby.tr.md +11 -1
  7. data/lib/lunixi/bank_connect.rb +340 -0
  8. data/lib/lunixi/bank_connect_filters.rb +114 -0
  9. data/lib/lunixi/bank_connect_values.rb +205 -0
  10. data/lib/lunixi/bank_transfer.rb +106 -0
  11. data/lib/lunixi/card_requests.rb +171 -0
  12. data/lib/lunixi/client.rb +57 -16
  13. data/lib/lunixi/direct_method_payment_request.rb +245 -0
  14. data/lib/lunixi/enabled_installments.rb +28 -0
  15. data/lib/lunixi/errors.rb +69 -3
  16. data/lib/lunixi/fraud.rb +81 -5
  17. data/lib/lunixi/identity.rb +94 -0
  18. data/lib/lunixi/identity_values.rb +28 -0
  19. data/lib/lunixi/insurance.rb +294 -0
  20. data/lib/lunixi/insurance_request.rb +134 -0
  21. data/lib/lunixi/insurance_values.rb +200 -0
  22. data/lib/lunixi/kyc.rb +189 -0
  23. data/lib/lunixi/kyc_values.rb +158 -0
  24. data/lib/lunixi/marketplace.rb +268 -0
  25. data/lib/lunixi/marketplace_values.rb +86 -0
  26. data/lib/lunixi/method_fields.rb +142 -0
  27. data/lib/lunixi/money.rb +7 -4
  28. data/lib/lunixi/order_details.rb +115 -0
  29. data/lib/lunixi/payment_link_filters.rb +32 -0
  30. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  31. data/lib/lunixi/payment_link_rules.rb +132 -0
  32. data/lib/lunixi/payment_link_values.rb +136 -0
  33. data/lib/lunixi/payment_links.rb +152 -0
  34. data/lib/lunixi/payment_values.rb +86 -0
  35. data/lib/lunixi/payments.rb +170 -8
  36. data/lib/lunixi/physical_pos.rb +183 -0
  37. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  38. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  39. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  40. data/lib/lunixi/physical_pos_filters.rb +58 -0
  41. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  42. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  43. data/lib/lunixi/physical_pos_management.rb +326 -0
  44. data/lib/lunixi/physical_pos_money.rb +46 -0
  45. data/lib/lunixi/physical_pos_request.rb +126 -0
  46. data/lib/lunixi/physical_pos_responses.rb +102 -0
  47. data/lib/lunixi/physical_pos_results.rb +52 -0
  48. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  49. data/lib/lunixi/physical_pos_value.rb +43 -0
  50. data/lib/lunixi/physical_pos_values.rb +203 -0
  51. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  52. data/lib/lunixi/product_webhooks.rb +106 -0
  53. data/lib/lunixi/promissory_note.rb +155 -0
  54. data/lib/lunixi/reference.rb +41 -0
  55. data/lib/lunixi/route_request.rb +121 -0
  56. data/lib/lunixi/route_response.rb +101 -0
  57. data/lib/lunixi/route_table.rb +128 -0
  58. data/lib/lunixi/route_value.rb +60 -0
  59. data/lib/lunixi/sanction.rb +244 -0
  60. data/lib/lunixi/sanction_values.rb +132 -0
  61. data/lib/lunixi/split_payment.rb +150 -0
  62. data/lib/lunixi/subscription_resources.rb +357 -0
  63. data/lib/lunixi/subscription_values.rb +233 -0
  64. data/lib/lunixi/subscriptions.rb +202 -0
  65. data/lib/lunixi/version.rb +1 -1
  66. data/lib/lunixi/wallet.rb +153 -0
  67. data/lib/lunixi/wallet_resources.rb +407 -0
  68. data/lib/lunixi/wallet_routes.rb +126 -0
  69. data/lib/lunixi/wallet_values.rb +71 -0
  70. data/lib/lunixi/wire_money.rb +67 -0
  71. data/lib/lunixi.rb +58 -0
  72. metadata +59 -1
@@ -0,0 +1,155 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+
5
+ module Lunixi
6
+ # Most rows of a promissory-note schedule (and most notes of a payment).
7
+ PROMISSORY_NOTE_MAX_SCHEDULE_ITEMS = 24
8
+
9
+ # Status of one note (notes[].status).
10
+ module PromissoryNoteStatus
11
+ ISSUED = 'ISSUED'
12
+ PAID = 'PAID'
13
+ PROTESTED = 'PROTESTED'
14
+ CANCELLED = 'CANCELLED'
15
+
16
+ ALL = [ISSUED, PAID, PROTESTED, CANCELLED].freeze
17
+ end
18
+
19
+ # Document type of the issued notes, from your provider connection settings.
20
+ module PromissoryNoteDocumentType
21
+ PROMISSORY_NOTE = 'PROMISSORY_NOTE'
22
+ PAYMENT_ORDER = 'PAYMENT_ORDER'
23
+
24
+ ALL = [PROMISSORY_NOTE, PAYMENT_ORDER].freeze
25
+ end
26
+
27
+ # Per-note result of payments.cancel_promissory_notes (cancelResults[].result).
28
+ module PromissoryNoteCancelResult
29
+ CANCELLED = 'CANCELLED'
30
+ # The note was already cancelled.
31
+ ALREADY_CLOSED = 'ALREADY_CLOSED'
32
+ # The note was collected or protested; it cannot be cancelled.
33
+ NOT_CANCELLABLE = 'NOT_CANCELLABLE'
34
+ # The note was not cancelled; errorCode tells whether to try again.
35
+ FAILED = 'FAILED'
36
+
37
+ ALL = [CANCELLED, ALREADY_CLOSED, NOT_CANCELLABLE, FAILED].freeze
38
+ end
39
+
40
+ # cancelResults[].errorCode: a Lunixi code; nil for CANCELLED and ALREADY_CLOSED.
41
+ module PromissoryNoteCancelErrorCode
42
+ # The note was collected or cannot be cancelled (NOT_CANCELLABLE).
43
+ NOT_CANCELLABLE = 'payment.promissory_note.not_cancellable'
44
+ # Temporary: the provider could not be reached; cancel again later (FAILED).
45
+ PROVIDER_UNAVAILABLE = 'payment.promissory_note.provider_unavailable'
46
+ # Permanent: the cancellation was refused (FAILED).
47
+ CANCEL_REJECTED = 'payment.promissory_note.cancel_rejected'
48
+
49
+ ALL = [NOT_CANCELLABLE, PROVIDER_UNAVAILABLE, CANCEL_REJECTED].freeze
50
+ end
51
+
52
+ # Language of the printable notes.
53
+ module PromissoryNoteDocumentLocale
54
+ TR = 'tr-TR'
55
+ EN = 'en-GB'
56
+
57
+ ALL = [TR, EN].freeze
58
+ end
59
+
60
+ # Webhook events of a note (payment.* envelope, payload promissoryNote).
61
+ module PromissoryNoteEvents
62
+ PAID = 'payment.promissory_note.paid'
63
+ PROTESTED = 'payment.promissory_note.protested'
64
+ CANCELLED = 'payment.promissory_note.cancelled'
65
+
66
+ ALL = [PAID, PROTESTED, CANCELLED].freeze
67
+ end
68
+
69
+ # Plan rules of a PROMISSORY_NOTE payment checked before sending: either a schedule of
70
+ # { amount, dueDate } rows or a noteCount, never both. That a due date lies in the future and that
71
+ # the note count fits your provider connection is checked by the gateway.
72
+ module PromissoryNotePlan
73
+ DUE_DATE_PATTERN = /\A([0-9]{4})-([0-9]{2})-([0-9]{2})\z/
74
+ NOTE_COUNT_PATTERN = /\A[1-9][0-9]?\z/
75
+ SERIAL_NUMBER_PATTERN = /\A[A-Za-z0-9-]{4,64}\z/
76
+
77
+ module_function
78
+
79
+ # 1–24 rows { amount, dueDate }: positive minor-unit strings, YYYY-MM-DD calendar dates in
80
+ # non-decreasing order. Returns string-keyed copies of the rows.
81
+ def schedule!(rows, path = 'promissoryNote.schedule')
82
+ raise ConfigurationError, "#{path} must be a nonempty list of { amount, dueDate } rows" unless rows.is_a?(Array) && !rows.empty?
83
+ raise ConfigurationError, "#{path} can have at most #{PROMISSORY_NOTE_MAX_SCHEDULE_ITEMS} rows" if rows.size > PROMISSORY_NOTE_MAX_SCHEDULE_ITEMS
84
+
85
+ previous = nil
86
+ rows.each_with_index.map do |row, index|
87
+ row_path = "#{path}[#{index}]"
88
+ raise ConfigurationError, "#{row_path} must be an object { amount, dueDate }" unless row.is_a?(Hash)
89
+
90
+ data = row.transform_keys(&:to_s)
91
+ raise ConfigurationError, "#{row_path} has unknown fields; a row is { amount, dueDate }" unless (data.keys - %w[amount dueDate]).empty?
92
+
93
+ Money.minor(data['amount'])
94
+ raise ConfigurationError, "#{row_path}.dueDate must be a calendar date in YYYY-MM-DD form" unless calendar_date?(data['dueDate'])
95
+ raise ConfigurationError, "#{row_path}.dueDate must not be earlier than the previous row" if previous && data['dueDate'] < previous
96
+
97
+ previous = data['dueDate']
98
+ { 'amount' => data['amount'], 'dueDate' => data['dueDate'] }
99
+ end
100
+ end
101
+
102
+ # Number of notes when no schedule is given: 1–24, sent as a string.
103
+ def note_count!(value, path = 'promissoryNote.noteCount')
104
+ text = value.is_a?(Integer) ? value.to_s : value
105
+ unless text.is_a?(String) && text.match?(NOTE_COUNT_PATTERN) && text.to_i <= PROMISSORY_NOTE_MAX_SCHEDULE_ITEMS
106
+ raise ConfigurationError, "#{path} must be a number of notes from 1 to #{PROMISSORY_NOTE_MAX_SCHEDULE_ITEMS}"
107
+ end
108
+
109
+ text
110
+ end
111
+
112
+ # The promissoryNote block of direct/payment: exactly one of schedule or noteCount; a schedule
113
+ # must add up to amount.
114
+ def plan!(block, amount, path = 'promissoryNote')
115
+ raise ConfigurationError, "#{path} must be an object" unless block.is_a?(Hash)
116
+
117
+ schedule = block['schedule']
118
+ note_count = block['noteCount']
119
+ raise ConfigurationError, "#{path}: send either schedule or noteCount, not both" if !schedule.nil? && !note_count.nil?
120
+ raise ConfigurationError, "#{path} needs the plan: a schedule ([{ amount, dueDate }]) or a noteCount" if schedule.nil? && note_count.nil?
121
+ return note_count!(note_count, "#{path}.noteCount") unless note_count.nil?
122
+
123
+ rows = schedule!(schedule, "#{path}.schedule")
124
+ total = rows.sum { |row| row['amount'].to_i }
125
+ raise ConfigurationError, "#{path}.schedule must add up to amount" unless total == Money.minor(amount).to_i
126
+
127
+ rows
128
+ end
129
+
130
+ # Serial numbers to cancel: 1–24 note serial numbers from payments.get_promissory_notes.
131
+ def serial_numbers!(values)
132
+ unless values.is_a?(Array) && !values.empty? && values.size <= PROMISSORY_NOTE_MAX_SCHEDULE_ITEMS
133
+ raise ConfigurationError, "serial_numbers must list 1 to #{PROMISSORY_NOTE_MAX_SCHEDULE_ITEMS} serial numbers; leave it out to cancel every open note"
134
+ end
135
+ unless values.all? { |value| value.is_a?(String) && value.match?(SERIAL_NUMBER_PATTERN) }
136
+ raise ConfigurationError, 'serial_numbers contains an invalid serial number (letters, digits and -, 4 to 64 characters)'
137
+ end
138
+
139
+ values.dup
140
+ end
141
+
142
+ def document_locale!(value)
143
+ return value if PromissoryNoteDocumentLocale::ALL.include?(value)
144
+
145
+ raise ConfigurationError, "locale must be one of #{PromissoryNoteDocumentLocale::ALL.join(', ')}"
146
+ end
147
+
148
+ def calendar_date?(value)
149
+ match = value.is_a?(String) && DUE_DATE_PATTERN.match(value)
150
+ match ? Date.valid_date?(match[1].to_i, match[2].to_i, match[3].to_i) : false
151
+ end
152
+
153
+ private_class_method :calendar_date?
154
+ end
155
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Lunixi address dictionary for Türkiye (province -> district -> neighborhood). The codes fill an
5
+ # ADDRESS input field, e.g. { provinceCode:, districtCode:, neighborhoodCode:, line: }. The answer is
6
+ # the gateway envelope with data.items [{ code, name }]; an empty list means the data for that level
7
+ # is not published yet.
8
+ class Reference
9
+ BASE = '/api/v1/reference/tr-address'
10
+ PROVINCE_CODE_PATTERN = /\A(0[1-9]|[1-7][0-9]|8[01])\z/
11
+ DISTRICT_CODE_PATTERN = /\A[0-9]{1,12}\z/
12
+ attr_reader :client
13
+
14
+ def initialize(client)
15
+ @client = client
16
+ end
17
+
18
+ # Provinces with their Lunixi code (01–81).
19
+ def list_provinces
20
+ client.request('GET', "#{BASE}/provinces", signed: false)
21
+ end
22
+
23
+ # Districts of a province (province_code 01–81).
24
+ def list_districts(province_code)
25
+ unless province_code.is_a?(String) && province_code.match?(PROVINCE_CODE_PATTERN)
26
+ raise ConfigurationError, 'province_code must be a two-digit province code from 01 to 81'
27
+ end
28
+
29
+ client.request('GET', "#{BASE}/districts", query: { provinceCode: province_code }, signed: false)
30
+ end
31
+
32
+ # Neighborhoods of a district (district_code from list_districts).
33
+ def list_neighborhoods(district_code)
34
+ unless district_code.is_a?(String) && district_code.match?(DISTRICT_CODE_PATTERN)
35
+ raise ConfigurationError, 'district_code must be a district code (digits) from list_districts'
36
+ end
37
+
38
+ client.request('GET', "#{BASE}/neighborhoods", query: { districtCode: district_code }, signed: false)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Request plumbing shared by the route-table clients (Wallet, Sanction, bank-connect transfers and
5
+ # FX, and the RouteTable products: subscriptions, KYC, identity, marketplace) and the bank-connect and
6
+ # insurance clients: route descriptions in the shared catalog's shape, wire keys, path segments and
7
+ # query values. Single values are checked by RouteValue; answers and pages are read by RouteResponse.
8
+ # Every check runs before anything is sent and names the field, never its value. Not a public API.
9
+ module RouteRequest
10
+ # Idempotency-Key of the bank-connect and insurance routes: 8–200 printable ASCII characters.
11
+ PRINTABLE_IDEMPOTENCY_KEY = /\A[\x21-\x7E]{8,200}\z/
12
+ PRINTABLE_KEY_ROUTE = %r{\A/api/v1/(?:bank-connect|insurance)(?:[/?]|\z)}
13
+
14
+ module_function
15
+
16
+ # One route in the shared catalog's shape: method, path and the given fields (idempotency_key:,
17
+ # required:, optional:, any_of:, query:, binary:, screening:) under their wire names.
18
+ def route(method, path, **fields)
19
+ described = { 'method' => method, 'path' => path }
20
+ fields.each { |name, value| described[camel(name.to_s)] = value.is_a?(Array) ? value.dup.freeze : value }
21
+ described.freeze
22
+ end
23
+
24
+ # The path template with every :name segment filled from params (trimmed, percent-encoded).
25
+ def path!(template, params)
26
+ template.gsub(/:([A-Za-z]+)/) do
27
+ name = Regexp.last_match(1)
28
+ value = params[name]
29
+ raise ConfigurationError, "#{name} is required." unless value.is_a?(String) && !value.strip.empty?
30
+
31
+ PhysicalPosIdentifiers.path_id(value.strip, name)
32
+ end
33
+ end
34
+
35
+ # A body with wire keys (String or Symbol, the wire name or its snake_case form); nil values are left
36
+ # out. An unknown key, a key given twice or a missing required field raises ConfigurationError.
37
+ def fields!(value, required, optional, label)
38
+ given = wire_keys!(value, required + optional, label)
39
+ missing = required.reject { |key| present?(given[key]) }
40
+ raise ConfigurationError, "#{label} requires #{missing.join(', ')}." unless missing.empty?
41
+
42
+ given
43
+ end
44
+
45
+ def wire_keys!(value, allowed, label, kind = 'field')
46
+ raise ConfigurationError, "#{label} must be a Hash." unless value.is_a?(Hash)
47
+
48
+ unknown = []
49
+ seen = []
50
+ given = {}
51
+ value.each do |key, entry|
52
+ raise ConfigurationError, "#{label} keys must be strings or symbols." unless key.is_a?(String) || key.is_a?(Symbol)
53
+
54
+ name = key.to_s
55
+ wire = allowed.include?(name) ? name : camel(name)
56
+ next unknown << name unless allowed.include?(wire)
57
+ raise ConfigurationError, "#{label} #{kind} '#{wire}' is given twice." if seen.include?(wire)
58
+
59
+ seen << wire
60
+ given[wire] = entry unless entry.nil?
61
+ end
62
+ return given if unknown.empty?
63
+
64
+ raise ConfigurationError, "Unknown #{label} #{kind}(s): #{unknown.join(', ')}. Allowed: " \
65
+ "#{allowed.empty? ? 'none' : allowed.join(', ')}. The gateway rejects unknown #{kind}s with 400."
66
+ end
67
+
68
+ # Query parameters checked against the route's list; nil and '' are left out. Values are Strings,
69
+ # Integers or booleans.
70
+ def query!(filters, allowed, label)
71
+ return {} if filters.nil?
72
+
73
+ given = wire_keys!(filters, allowed, label, 'filter')
74
+ given.each_with_object({}) do |(key, value), query|
75
+ next if value == ''
76
+ unless value.is_a?(String) || value.is_a?(Integer) || value == true || value == false
77
+ raise ConfigurationError, "#{label} filter '#{key}' must be a string, an integer or a boolean."
78
+ end
79
+
80
+ query[key] = value
81
+ end
82
+ end
83
+
84
+ def printable_idempotency_key!(key)
85
+ unless key.is_a?(String) && key.match?(PRINTABLE_IDEMPOTENCY_KEY)
86
+ raise ConfigurationError, 'The Idempotency-Key must be 8–200 printable ASCII characters without spaces; it is sent ' \
87
+ 'exactly as given. Reuse the same key when retrying the same operation.'
88
+ end
89
+
90
+ key
91
+ end
92
+
93
+ def present?(value)
94
+ !(value.nil? || value == '' || (value.is_a?(Array) && value.empty?))
95
+ end
96
+
97
+ def compact(hash)
98
+ hash.compact
99
+ end
100
+
101
+ def camel(name)
102
+ name.gsub(/_([a-z0-9])/) { Regexp.last_match(1).upcase }
103
+ end
104
+
105
+ # A Hash with String wire keys (a snake_case key is sent camelCase); nil values are left out. Nested
106
+ # values are sent as given. A key given twice raises ConfigurationError.
107
+ def wire_hash!(value, label)
108
+ value = value.to_h if !value.is_a?(Hash) && value.respond_to?(:to_h) && !value.is_a?(Array) && !value.nil?
109
+ raise ConfigurationError, "#{label} must be a Hash." unless value.is_a?(Hash)
110
+
111
+ value.each_with_object({}) do |(key, entry), plain|
112
+ raise ConfigurationError, "#{label} keys must be strings or symbols." unless key.is_a?(String) || key.is_a?(Symbol)
113
+
114
+ wire = camel(key.to_s)
115
+ raise ConfigurationError, "#{label} field '#{wire}' is given twice." if plain.key?(wire)
116
+
117
+ plain[wire] = entry unless entry.nil?
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,101 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # One page of a list. next_cursor is opaque: pass it back unchanged as cursor: (page_token: for the
5
+ # subscription, plan, customer, card and invoice lists), or use the iterate methods. total_count is nil
6
+ # unless the list counts rows; page_size is the page size of a subscription list (nil elsewhere). raw is
7
+ # the envelope's data.
8
+ ListPage = Struct.new(:items, :next_cursor, :has_more, :total_count, :raw, :page_size, keyword_init: true) do
9
+ def has_more? # rubocop:disable Naming/PredicatePrefix -- public ListPage API (README)
10
+ has_more == true
11
+ end
12
+ end
13
+
14
+ # Answer reading shared by the route-table clients: the envelope's data, list pages (ListPage) and
15
+ # iteration over every page. Not a public API.
16
+ module RouteResponse
17
+ module_function
18
+
19
+ # The envelope's data (the answer itself when there is none).
20
+ def unwrap(response)
21
+ response.is_a?(Hash) && response.key?('data') ? response['data'] : response
22
+ end
23
+
24
+ # A list answer: rows are data (an array), data.items or the first array member of data; paging is
25
+ # the envelope's top-level pageInfo (a copy inside data is read as a fallback) or data.nextCursor.
26
+ def page(response)
27
+ data = unwrap(response)
28
+ container = data.is_a?(Hash) ? data : {}
29
+ info = hash_at(response, 'pageInfo') || hash_at(container, 'pageInfo')
30
+ cursor = text(info && info['nextCursor']) || text(container['nextCursor'])
31
+ has_more = info&.key?('hasMore') ? info['hasMore'] == true && !cursor.nil? : !cursor.nil?
32
+ total = [info && info['totalCount'], container['totalCount']].find { |value| value.is_a?(Integer) }
33
+ ListPage.new(items: data.is_a?(Array) ? data : rows(container), next_cursor: cursor, has_more: has_more, total_count: total, raw: data)
34
+ end
35
+
36
+ def rows(container)
37
+ return container['items'] if container['items'].is_a?(Array)
38
+
39
+ container.values.find { |value| value.is_a?(Array) } || []
40
+ end
41
+
42
+ def hash_at(value, key)
43
+ value[key] if value.is_a?(Hash) && value[key].is_a?(Hash)
44
+ end
45
+
46
+ def text(value)
47
+ value.is_a?(String) && !value.empty? ? value : nil
48
+ end
49
+
50
+ # A list answer of the RouteTable products: rows are data (an array) or data.items / operations /
51
+ # rows (objects only); the cursor is pageInfo.nextCursor or endCursor (a pageInfo that names neither
52
+ # is the last page), else nextCursor or nextPageToken in data or at the envelope root; total_count is
53
+ # pageInfo.totalCount, data.totalCount or data.total. has_more is pageInfo.hasMore when it is a boolean.
54
+ def cursor_page(response)
55
+ data = unwrap(response)
56
+ container = data.is_a?(Hash) ? data : {}
57
+ root = response.is_a?(Hash) ? response : {}
58
+ rows = data.is_a?(Array) ? data : %w[items operations rows].map { |key| container[key] }.find { |value| value.is_a?(Array) } || []
59
+ info = hash_at(container, 'pageInfo') || hash_at(root, 'pageInfo')
60
+ token = page_token(info, container, root)
61
+ total = [info && info['totalCount'], container['totalCount'], container['total']].find { |value| value.is_a?(Integer) }
62
+ has_more = info && [true, false].include?(info['hasMore']) ? info['hasMore'] : !token.nil?
63
+ ListPage.new(items: rows.grep(Hash), next_cursor: token, has_more: has_more, total_count: total, raw: data)
64
+ end
65
+
66
+ def page_token(info, container, root)
67
+ if info
68
+ cursor = text(info['nextCursor']) || text(info['endCursor'])
69
+ return cursor if cursor || info.key?('nextCursor') || info.key?('endCursor')
70
+ end
71
+ [container['nextCursor'], container['nextPageToken'], root['nextPageToken'], root['nextCursor']].map { |value| text(value) }.compact.first
72
+ end
73
+
74
+ # Answers that put their fields at the envelope root and/or under data: both, merged (data wins).
75
+ def merge_root(response)
76
+ return {} unless response.is_a?(Hash)
77
+
78
+ data = response['data'].is_a?(Hash) ? response['data'] : {}
79
+ response.except('data').merge(data)
80
+ end
81
+
82
+ # Every item of every page, fetching the next page only when it is needed. cursor_key is the filter
83
+ # the next cursor goes back in. Without a block it returns an Enumerator.
84
+ def each_item(filters, block, cursor_key = :cursor, &fetch)
85
+ items = Enumerator.new do |yielder|
86
+ query = filters.transform_keys(&:to_sym)
87
+ loop do
88
+ page = fetch.call(query)
89
+ page.items.each { |item| yielder << item }
90
+ break unless page.has_more && page.next_cursor
91
+
92
+ query = query.reject { |key, _| RouteRequest.camel(key.to_s) == RouteRequest.camel(cursor_key.to_s) }.merge(cursor_key => page.next_cursor)
93
+ end
94
+ end
95
+ return items unless block
96
+
97
+ items.each(&block)
98
+ nil
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Sends one route of a product route table (SUBSCRIPTION_ROUTES, KYC_ROUTES, IDENTITY_ROUTES,
5
+ # MARKETPLACE_ROUTES). Each route is described in the shared catalog's shape:
6
+ #
7
+ # method, path the HTTP method and path template (:name filled from params)
8
+ # stepUp sent with the per-request signature; otherwise the access token only
9
+ # idempotencyKey 'required' | 'optional' | 'none' (the Idempotency-Key header)
10
+ # required/optional the body fields; any other field is refused before sending
11
+ # free the body is a Hash the gateway validates (no field list)
12
+ # optionalBody an empty body is sent as no body
13
+ # query / anyQuery the accepted filters; anyQuery accepts any scalar filter
14
+ #
15
+ # Every check runs before anything is sent and raises ConfigurationError naming the field, never its
16
+ # value (card data and document images included). Subscription and marketplace routes carry money:
17
+ # bodies, filters and answers are checked with WireMoney.validate_wire. Not a public API.
18
+ class RouteTable
19
+ MONEY_ROUTE = %r{\A/api/v1/(?:subscriptions|marketplace)(?:/|\z)}
20
+ # Routes whose Idempotency-Key is any non-empty string without control characters (sent trimmed).
21
+ KEY_ROUTE = %r{\A/api/(?:v1/(?:subscriptions|kyc|identity|marketplace)|panel/v1/subscriptions/portal)(?:[/?]|\z)}
22
+ CONTROL_CHARACTERS = /[\x00-\x1f\x7f]/
23
+ KEY_RULES = %w[required optional none].freeze
24
+
25
+ def self.idempotency_key!(key, name = nil)
26
+ value = key.is_a?(String) ? key.strip : ''
27
+ if value.empty? || value.match?(CONTROL_CHARACTERS)
28
+ raise ConfigurationError, "The Idempotency-Key#{" of #{name}" if name} must be a non-empty string without control characters."
29
+ end
30
+
31
+ value
32
+ end
33
+
34
+ # The request's own idempotencyKey or the idempotency_key: argument (both given: they must agree).
35
+ def self.idempotency_key_of(name, request, key)
36
+ own = request.is_a?(Hash) ? request['idempotencyKey'] : nil
37
+ own = own.is_a?(String) && !own.strip.empty? ? own.strip : nil
38
+ given = key.is_a?(String) && !key.strip.empty? ? key.strip : nil
39
+ raise ConfigurationError, "#{name}: the request's idempotencyKey and the idempotency_key: argument differ." if own && given && own != given
40
+
41
+ given || own || key
42
+ end
43
+
44
+ def initialize(client, routes)
45
+ @client = client
46
+ @routes = routes
47
+ end
48
+
49
+ # The raw answer of one route. params: path segments by wire name; query: filters; body: the request
50
+ # Hash (wire names, snake_case works too).
51
+ def call(name, params: {}, query: nil, body: nil, idempotency_key: nil)
52
+ route = @routes.fetch(name) { raise ArgumentError, "Unknown route #{name}." }
53
+ path = RouteRequest.path!(route['path'], params)
54
+ key = key!(name, route['idempotencyKey'] || 'none', idempotency_key)
55
+ filters = query.nil? ? {} : filters!(name, route, query)
56
+ payload = body!(name, route, body)
57
+ money = path.match?(MONEY_ROUTE)
58
+ if money
59
+ WireMoney.validate_wire(payload)
60
+ WireMoney.validate_wire(filters)
61
+ end
62
+ response = @client.request(route['method'], path, body: payload, query: filters, idempotency_key: key, signed: route['stepUp'] == true)
63
+ WireMoney.validate_wire(response) if money
64
+ response
65
+ end
66
+
67
+ # The envelope's data.
68
+ def data(name, **)
69
+ RouteResponse.unwrap(call(name, **))
70
+ end
71
+
72
+ # A Lunixi::ListPage.
73
+ def page(name, **)
74
+ RouteResponse.cursor_page(call(name, **))
75
+ end
76
+
77
+ # A subscription list: the cursor is nextPageToken (send it back as page_token:) and page_size the
78
+ # envelope's pageSize (the row count when there is none).
79
+ def token_page(name, **)
80
+ response = call(name, **)
81
+ page = RouteResponse.cursor_page(response)
82
+ size = response.is_a?(Hash) && response['pageSize'].is_a?(Integer) ? response['pageSize'] : page.items.length
83
+ ListPage.new(items: page.items, next_cursor: page.next_cursor, has_more: page.has_more, total_count: page.total_count,
84
+ raw: page.raw, page_size: size)
85
+ end
86
+
87
+ private
88
+
89
+ def key!(name, rule, key)
90
+ raise ArgumentError, "Unknown Idempotency-Key rule #{rule}." unless KEY_RULES.include?(rule)
91
+
92
+ if key.nil?
93
+ return nil unless rule == 'required'
94
+
95
+ raise ConfigurationError, "A stable Idempotency-Key is required for #{name}. Reuse the same key when retrying the same operation."
96
+ end
97
+ raise ConfigurationError, "#{name} does not take an Idempotency-Key." if rule == 'none'
98
+
99
+ self.class.idempotency_key!(key, name)
100
+ end
101
+
102
+ def filters!(name, route, query)
103
+ return RouteRequest.query!(query, route['query'] || [], name) unless route['anyQuery']
104
+
105
+ RouteRequest.wire_hash!(query, "#{name} filters").each_with_object({}) do |(key, value), filters|
106
+ next if value == ''
107
+ unless value.is_a?(String) || value.is_a?(Integer) || value == true || value == false
108
+ raise ConfigurationError, "#{name} filter '#{key}' must be a string, an integer or a boolean."
109
+ end
110
+
111
+ filters[key] = value
112
+ end
113
+ end
114
+
115
+ def body!(name, route, body)
116
+ if route.key?('required') || route.key?('optional')
117
+ plain = RouteRequest.fields!(body || {}, route['required'] || [], route['optional'] || [], name)
118
+ elsif route['free']
119
+ plain = RouteRequest.wire_hash!(body.nil? && route['optionalBody'] ? {} : body, "#{name} body")
120
+ else
121
+ raise ConfigurationError, "#{name} takes no body." unless body.nil? || body == {}
122
+
123
+ return nil
124
+ end
125
+ route['optionalBody'] && plain.empty? ? nil : plain
126
+ end
127
+ end
128
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Single request values shared by the route-table clients: texts, currency codes, times and closed
5
+ # value lists. Every check names the field, never its value. Not a public API.
6
+ module RouteValue
7
+ CURRENCY = /\A[A-Z]{3}\z/
8
+
9
+ module_function
10
+
11
+ # A trimmed non-empty String, at most max characters when given.
12
+ def text!(value, field, max = nil)
13
+ raise ConfigurationError, "'#{field}' is required." unless value.is_a?(String) && !value.strip.empty?
14
+
15
+ text = value.strip
16
+ raise ConfigurationError, "'#{field}' must be at most #{max} characters." if max && text.length > max
17
+
18
+ text
19
+ end
20
+
21
+ def currency!(value, field)
22
+ currency = value.is_a?(String) ? value.strip.upcase : ''
23
+ raise ConfigurationError, "'#{field}' must be an ISO 4217 code such as TRY." unless currency.match?(CURRENCY)
24
+
25
+ currency
26
+ end
27
+
28
+ # A Time (sent as ISO 8601 UTC) or an ISO 8601 string with a time zone (sent trimmed).
29
+ def iso_time!(value, field)
30
+ return value.getutc.strftime('%Y-%m-%dT%H:%M:%S.%LZ') if value.is_a?(Time)
31
+ return value.strip if value.is_a?(String) && !value.strip.empty?
32
+
33
+ raise ConfigurationError, "'#{field}' must be a Time or an ISO 8601 string with a time zone."
34
+ end
35
+
36
+ # The instant of a Time or an ISO 8601 string, nil when it cannot be read.
37
+ def instant(value)
38
+ return value if value.is_a?(Time)
39
+ return nil unless value.is_a?(String) && !value.strip.empty?
40
+
41
+ Time.iso8601(value.strip)
42
+ rescue ArgumentError
43
+ nil
44
+ end
45
+
46
+ # nil or '' is nil; anything else must be a String.
47
+ def optional_text(value, field)
48
+ return nil if value.nil? || value == ''
49
+ raise ConfigurationError, "'#{field}' must be a string." unless value.is_a?(String)
50
+
51
+ value
52
+ end
53
+
54
+ def one_of!(value, allowed, field)
55
+ return value if allowed.include?(value)
56
+
57
+ raise ConfigurationError, "'#{field}' must be one of #{allowed.join(', ')}."
58
+ end
59
+ end
60
+ end