lunixi-sdk 1.2.2 → 1.3.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 (69) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -0
  3. data/README.md +262 -9
  4. data/README.tr.md +266 -7
  5. data/lib/lunixi/bank_connect.rb +340 -0
  6. data/lib/lunixi/bank_connect_filters.rb +114 -0
  7. data/lib/lunixi/bank_connect_values.rb +205 -0
  8. data/lib/lunixi/bank_transfer.rb +106 -0
  9. data/lib/lunixi/card_requests.rb +150 -0
  10. data/lib/lunixi/client.rb +57 -16
  11. data/lib/lunixi/direct_method_payment_request.rb +243 -0
  12. data/lib/lunixi/enabled_installments.rb +28 -0
  13. data/lib/lunixi/errors.rb +69 -3
  14. data/lib/lunixi/fraud.rb +81 -5
  15. data/lib/lunixi/identity.rb +94 -0
  16. data/lib/lunixi/identity_values.rb +28 -0
  17. data/lib/lunixi/insurance.rb +294 -0
  18. data/lib/lunixi/insurance_request.rb +134 -0
  19. data/lib/lunixi/insurance_values.rb +200 -0
  20. data/lib/lunixi/kyc.rb +189 -0
  21. data/lib/lunixi/kyc_values.rb +158 -0
  22. data/lib/lunixi/marketplace.rb +264 -0
  23. data/lib/lunixi/marketplace_values.rb +86 -0
  24. data/lib/lunixi/method_fields.rb +142 -0
  25. data/lib/lunixi/money.rb +7 -4
  26. data/lib/lunixi/payment_link_filters.rb +32 -0
  27. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  28. data/lib/lunixi/payment_link_rules.rb +132 -0
  29. data/lib/lunixi/payment_link_values.rb +134 -0
  30. data/lib/lunixi/payment_links.rb +152 -0
  31. data/lib/lunixi/payment_values.rb +86 -0
  32. data/lib/lunixi/payments.rb +154 -5
  33. data/lib/lunixi/physical_pos.rb +183 -0
  34. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  35. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  36. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  37. data/lib/lunixi/physical_pos_filters.rb +58 -0
  38. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  39. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  40. data/lib/lunixi/physical_pos_management.rb +326 -0
  41. data/lib/lunixi/physical_pos_money.rb +46 -0
  42. data/lib/lunixi/physical_pos_request.rb +126 -0
  43. data/lib/lunixi/physical_pos_responses.rb +102 -0
  44. data/lib/lunixi/physical_pos_results.rb +52 -0
  45. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  46. data/lib/lunixi/physical_pos_value.rb +43 -0
  47. data/lib/lunixi/physical_pos_values.rb +203 -0
  48. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  49. data/lib/lunixi/product_webhooks.rb +106 -0
  50. data/lib/lunixi/promissory_note.rb +155 -0
  51. data/lib/lunixi/reference.rb +41 -0
  52. data/lib/lunixi/route_request.rb +121 -0
  53. data/lib/lunixi/route_response.rb +101 -0
  54. data/lib/lunixi/route_table.rb +128 -0
  55. data/lib/lunixi/route_value.rb +60 -0
  56. data/lib/lunixi/sanction.rb +244 -0
  57. data/lib/lunixi/sanction_values.rb +132 -0
  58. data/lib/lunixi/split_payment.rb +145 -0
  59. data/lib/lunixi/subscription_resources.rb +355 -0
  60. data/lib/lunixi/subscription_values.rb +220 -0
  61. data/lib/lunixi/subscriptions.rb +202 -0
  62. data/lib/lunixi/version.rb +1 -1
  63. data/lib/lunixi/wallet.rb +153 -0
  64. data/lib/lunixi/wallet_resources.rb +402 -0
  65. data/lib/lunixi/wallet_routes.rb +123 -0
  66. data/lib/lunixi/wallet_values.rb +71 -0
  67. data/lib/lunixi/wire_money.rb +67 -0
  68. data/lib/lunixi.rb +57 -0
  69. metadata +58 -1
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Lunixi
6
+ # One verified physical POS webhook (frozen).
7
+ #
8
+ # id: the event id (the same transition always carries the same id). type: physical_pos.payment.*,
9
+ # physical_pos.fiscal_document.* or physical_pos.settlement.*. category: payment, fiscal_document,
10
+ # settlement or other (a type a later release may add). environment: LIVE or TEST when present.
11
+ # created_at: when the transition happened (ISO 8601), when present. history_seq: the payment's /
12
+ # document's historySeq, or nil (end-of-day events carry none). original: a reversal's original
13
+ # payment { 'paymentId', 'origin' } (origin API or DEVICE_DIRECT), nil on a root payment. cashier:
14
+ # { 'cashierId', 'cashierCode' } for a payment started from a device cashier session, nil otherwise
15
+ # (the payload then has no cashier key). device_sale?: true for physical_pos.payment.device_sale, a
16
+ # sale made directly on the device (data carries origin and deviceOccurredAt). data: the payload.
17
+ # raw: the whole envelope.
18
+ PhysicalPosWebhookEvent = Struct.new(:id, :type, :category, :environment, :created_at, :history_seq, :original, :cashier,
19
+ :device_sale, :data, :raw, keyword_init: true) do
20
+ def device_sale?
21
+ device_sale == true
22
+ end
23
+ end
24
+
25
+ # Verifies and reads a physical POS webhook. There is no way in without the signature: pass the exact
26
+ # raw request body, the request headers and your webhook secret (or a configured WebhookVerifier).
27
+ # The signature, event id and timestamp are checked by WebhookVerifier; any mismatch raises
28
+ # WebhookError before the body is read.
29
+ #
30
+ # event = Lunixi::PhysicalPosWebhook.parse(request.raw_post, request.headers.to_h, secret)
31
+ # handle_approval(event.data) if event.type == Lunixi::PhysicalPosEvents::PAYMENT_APPROVED
32
+ #
33
+ # The event body is the envelope's data; an envelope that carries it under payloadJson (an object or
34
+ # that object as a JSON string) is read the same way. The type comes from the signed body only.
35
+ # Amounts in the payload are minor-unit strings ("4500"), matching the HTTP API, and are checked
36
+ # after the signature.
37
+ #
38
+ # Delivery order is not guaranteed and an event can arrive more than once: deduplicate by id and
39
+ # ignore an event whose history_seq is not greater than the last one you applied for the same
40
+ # data['paymentId']. End-of-day events (category settlement) carry no historySeq; deduplicate them by
41
+ # id. When in doubt, read the payment with get_payment.
42
+ module PhysicalPosWebhook
43
+ PREFIX = 'physical_pos.'
44
+ CATEGORY_PAYMENT = 'payment'
45
+ CATEGORY_FISCAL_DOCUMENT = 'fiscal_document'
46
+ CATEGORY_SETTLEMENT = 'settlement'
47
+ CATEGORY_OTHER = 'other'
48
+
49
+ module_function
50
+
51
+ # secret_or_verifier: your webhook secret, [current, *previous] secrets during rotation, or a
52
+ # WebhookVerifier. tolerance (seconds) is used only when secrets are given.
53
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
54
+ verified = verifier_for(secret_or_verifier, tolerance).verify(raw_body, headers)
55
+ envelope = verified.raw
56
+ type = text(envelope['type']) || text(envelope['eventType']) || verified.type
57
+ raise WebhookError, "Not a physical POS webhook event (type: #{type || 'missing'})" unless type.is_a?(String) && type.start_with?(PREFIX)
58
+
59
+ data = payload(envelope)
60
+ validate_money(data)
61
+ seq = data['historySeq']
62
+ PhysicalPosWebhookEvent.new(
63
+ id: text(envelope['id']) || text(envelope['eventId']) || verified.id, type: type, category: category(type),
64
+ environment: text(envelope['environment']),
65
+ created_at: text(envelope['createdAt']) || text(envelope['occurredAt']) || text(envelope['timestamp']),
66
+ history_seq: seq.is_a?(Integer) ? seq : nil, original: original(data), cashier: cashier(data),
67
+ device_sale: type == PhysicalPosEvents::PAYMENT_DEVICE_SALE, data: data, raw: envelope
68
+ ).freeze
69
+ end
70
+
71
+ # The original payment of a reversal event: { 'paymentId', 'origin' } when data['original'] carries
72
+ # both as non-empty strings (other keys are dropped); otherwise nil (a root payment).
73
+ def original(data)
74
+ pair(data, 'original', 'paymentId', 'origin')
75
+ end
76
+
77
+ # The cashier of a payment event: { 'cashierId', 'cashierCode' } when data['cashier'] carries both
78
+ # as non-empty strings (other keys are dropped); otherwise nil (no cashier session).
79
+ def cashier(data)
80
+ pair(data, 'cashier', 'cashierId', 'cashierCode')
81
+ end
82
+
83
+ # payment, fiscal_document, settlement or other.
84
+ def category(type)
85
+ return CATEGORY_PAYMENT if type.start_with?("#{PREFIX}payment.")
86
+ return CATEGORY_FISCAL_DOCUMENT if type.start_with?("#{PREFIX}fiscal_document.")
87
+ return CATEGORY_SETTLEMENT if type.start_with?("#{PREFIX}settlement.")
88
+
89
+ CATEGORY_OTHER
90
+ end
91
+
92
+ def pair(data, name, first, second)
93
+ value = data.is_a?(Hash) ? data[name] : nil
94
+ return nil unless value.is_a?(Hash)
95
+
96
+ left = text(value[first])
97
+ right = text(value[second])
98
+ left && right ? { first => left, second => right }.freeze : nil
99
+ end
100
+
101
+ def verifier_for(secret_or_verifier, tolerance)
102
+ return secret_or_verifier if secret_or_verifier.is_a?(WebhookVerifier)
103
+
104
+ unless secret_or_verifier.is_a?(String) || (secret_or_verifier.is_a?(Array) && !secret_or_verifier.empty?)
105
+ raise ConfigurationError, 'Pass your webhook secret (or [current, *previous] secrets) or a WebhookVerifier'
106
+ end
107
+
108
+ secrets = Array(secret_or_verifier)
109
+ WebhookVerifier.new(secret: secrets.first, previous_secrets: secrets.drop(1), tolerance: tolerance)
110
+ end
111
+
112
+ def payload(envelope)
113
+ data = envelope['data']
114
+ return data if data.is_a?(Hash) && !data.empty?
115
+
116
+ carried = envelope['payloadJson']
117
+ carried = parse_payload_json(carried) if carried.is_a?(String)
118
+ return deep_freeze(carried) if carried.is_a?(Hash) && !carried.empty?
119
+
120
+ raise WebhookError, 'The physical POS webhook carries no event data (data / payloadJson)'
121
+ end
122
+
123
+ def parse_payload_json(text)
124
+ JSON.parse(text, max_nesting: 64)
125
+ rescue JSON::ParserError
126
+ raise WebhookError, 'The physical POS webhook payloadJson is not valid JSON', cause: nil
127
+ end
128
+
129
+ def validate_money(data)
130
+ PhysicalPosMoney.validate(data)
131
+ rescue ConfigurationError
132
+ raise WebhookError, 'The physical POS webhook carries a non-canonical amount (minor-unit string expected)', cause: nil
133
+ end
134
+
135
+ def text(value)
136
+ value.is_a?(String) && !value.empty? ? value : nil
137
+ end
138
+
139
+ def deep_freeze(value)
140
+ case value
141
+ when Hash then value.each_value { |entry| deep_freeze(entry) }
142
+ when Array then value.each { |entry| deep_freeze(entry) }
143
+ end
144
+ value.freeze
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # One verified bank-connect, bank-transfer or insurance webhook (frozen). id: the event id (the same on
5
+ # every redelivery; deduplicate on it). type: one of the product's event names. environment: TEST or
6
+ # LIVE when present. created_at: the envelope's createdAt. data: the documented data fields of the
7
+ # event (a field the event did not carry is nil; no other key is kept). raw: the whole envelope.
8
+ ProductWebhookEvent = Struct.new(:id, :type, :environment, :created_at, :data, :raw, keyword_init: true) do
9
+ def [](name)
10
+ data[name.to_s]
11
+ end
12
+ end
13
+
14
+ # Reads product webhooks through the signature check, never around it. Not a public API; use
15
+ # BankConnectWebhook, BankTransferWebhook or InsuranceWebhook.
16
+ module ProductWebhook
17
+ module_function
18
+
19
+ # fields: { event type => data field list }. Amounts in data must be canonical minor-unit strings.
20
+ def parse(raw_body, headers, secret_or_verifier, fields, label, tolerance)
21
+ verified = PhysicalPosWebhook.verifier_for(secret_or_verifier, tolerance).verify(raw_body, headers)
22
+ read(verified, fields, label)
23
+ end
24
+
25
+ # An event already verified by WebhookVerifier#verify (or #process).
26
+ def read(verified, fields, label)
27
+ raise ConfigurationError, 'Pass a Lunixi::VerifiedEvent from WebhookVerifier#verify' unless verified.is_a?(VerifiedEvent)
28
+
29
+ list = fields[verified.type]
30
+ raise WebhookError, "Not a #{label} webhook event (type: #{verified.type})" if list.nil?
31
+
32
+ data = list.to_h { |name| [name, verified.data[name]] }
33
+ begin
34
+ Money.validate_fields(data, response: true)
35
+ rescue ConfigurationError
36
+ raise WebhookError, "The #{label} webhook carries a non-canonical amount (minor-unit string expected)", cause: nil
37
+ end
38
+ envelope = verified.raw
39
+ ProductWebhookEvent.new(id: verified.id, type: verified.type, environment: text(envelope['environment']),
40
+ created_at: text(envelope['createdAt']), data: data.freeze, raw: envelope).freeze
41
+ end
42
+
43
+ def text(value)
44
+ value.is_a?(String) && !value.empty? ? value : nil
45
+ end
46
+ end
47
+
48
+ # bank_account.transaction.received (BankConnectEvents): data holds
49
+ # BANK_ACCOUNT_TRANSACTION_RECEIVED_FIELDS.
50
+ #
51
+ # event = Lunixi::BankConnectWebhook.parse(request.raw_post, request.headers.to_h, secret)
52
+ # book(event['transactionId'], event['amountMinor']) unless seen?(event.id)
53
+ module BankConnectWebhook
54
+ FIELDS = BankConnectEvents::ALL.to_h { |type| [type, BANK_ACCOUNT_TRANSACTION_RECEIVED_FIELDS] }.freeze
55
+
56
+ module_function
57
+
58
+ # secret_or_verifier: your webhook secret, [current, *previous] secrets during rotation, or a
59
+ # WebhookVerifier. Raises WebhookError for a bad signature or another event type.
60
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
61
+ ProductWebhook.parse(raw_body, headers, secret_or_verifier, FIELDS, 'bank account', tolerance)
62
+ end
63
+
64
+ def from_event(verified_event)
65
+ ProductWebhook.read(verified_event, FIELDS, 'bank account')
66
+ end
67
+ end
68
+
69
+ # bank_transfer.* (BankTransferEvents, Bank Connect transfers): data holds BANK_TRANSFER_WEBHOOK_FIELDS.
70
+ # The event says what happened; read the current state with bank_connect.transfers.get.
71
+ module BankTransferWebhook
72
+ FIELDS = BankTransferEvents::ALL.to_h { |type| [type, BANK_TRANSFER_WEBHOOK_FIELDS] }.freeze
73
+
74
+ module_function
75
+
76
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
77
+ ProductWebhook.parse(raw_body, headers, secret_or_verifier, FIELDS, 'bank transfer', tolerance)
78
+ end
79
+
80
+ def from_event(verified_event)
81
+ ProductWebhook.read(verified_event, FIELDS, 'bank transfer')
82
+ end
83
+ end
84
+
85
+ # insurance.* (InsuranceEvents). An order event's data holds INSURANCE_WEBHOOK_FIELDS; the lead event
86
+ # (insurance.lead.submitted) holds INSURANCE_LEAD_WEBHOOK_FIELDS and is not an order. Decide on the
87
+ # order from the webhook; get_order shows its state.
88
+ module InsuranceWebhook
89
+ FIELDS = InsuranceEvents::ORDER_EVENTS.to_h { |type| [type, INSURANCE_WEBHOOK_FIELDS] }
90
+ .merge(InsuranceEvents::LEAD_SUBMITTED => INSURANCE_LEAD_WEBHOOK_FIELDS).freeze
91
+
92
+ module_function
93
+
94
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
95
+ ProductWebhook.parse(raw_body, headers, secret_or_verifier, FIELDS, 'insurance', tolerance)
96
+ end
97
+
98
+ def from_event(verified_event)
99
+ ProductWebhook.read(verified_event, FIELDS, 'insurance')
100
+ end
101
+
102
+ def lead_event?(event)
103
+ InsuranceEvents::LEAD_EVENTS.include?(event.type)
104
+ end
105
+ end
106
+ end
@@ -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