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,340 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module Lunixi
6
+ # Bank accounts (/api/v1/bank-connect, product BANK_CONNECT): your connected bank accounts, balances
7
+ # and transactions.
8
+ #
9
+ # Every call is signed, reads included (an unsigned request is 401 AUTH_HEADERS_MISSING). Scopes:
10
+ # bank-connect:view for banks, connections, accounts and request_sync; bank-connect:transactions:view
11
+ # for balances and transactions. The key decides the environment: a TEST key reads only test accounts,
12
+ # a LIVE key only live ones. Connecting a bank and entering bank credentials happen in the Lunixi
13
+ # dashboard only; another organisation's or environment's record is 404 like a missing one.
14
+ #
15
+ # Filters are checked before anything is sent (BANK_CONNECT_FILTERS): an unknown filter, a value
16
+ # outside its set, limit outside 1–100, more than 100 account ids, a malformed amount or a bad date
17
+ # window raises ConfigurationError. Filter keys are the wire names (snake_case works too).
18
+ #
19
+ # Money movement is on transfers (Lunixi::BankConnectTransfers) and fx (Lunixi::BankConnectFx), for a
20
+ # connection whose capabilities include OUTGOING_TRANSFER / FX_EXCHANGE.
21
+ #
22
+ # Answers are the envelope's data; lists return a Lunixi::ListPage.
23
+ class BankConnect
24
+ BASE = '/api/v1/bank-connect'
25
+ attr_reader :transfers, :fx
26
+
27
+ def initialize(client, max_retries:, backoff:)
28
+ @client = client
29
+ invoker = BankTransferInvoker.new(client, max_retries: max_retries, backoff: backoff)
30
+ @transfers = BankConnectTransfers.new(invoker)
31
+ @fx = BankConnectFx.new(invoker)
32
+ end
33
+
34
+ # The bank catalogue: whether each bank can be connected and what is read from it.
35
+ def list_banks(**filters)
36
+ page('/banks', 'listBanks', filters)
37
+ end
38
+
39
+ def iterate_banks(**filters, &block)
40
+ RouteResponse.each_item(filters, block) { |query| list_banks(**query) }
41
+ end
42
+
43
+ # Your bank connections, newest first. status takes one value or an Array.
44
+ def list_connections(**filters)
45
+ page('/connections', 'listConnections', filters)
46
+ end
47
+
48
+ def iterate_connections(**filters, &block)
49
+ RouteResponse.each_item(filters, block) { |query| list_connections(**query) }
50
+ end
51
+
52
+ # 404 bank_connect.connection.not_found for an unknown connection.
53
+ def get_connection(connection_id)
54
+ read("/connections/#{segment(connection_id, 'connectionId')}")
55
+ end
56
+
57
+ # Your connected accounts, newest first, each with its data freshness.
58
+ def list_accounts(**filters)
59
+ page('/accounts', 'listAccounts', filters)
60
+ end
61
+
62
+ def iterate_accounts(**filters, &block)
63
+ RouteResponse.each_item(filters, block) { |query| list_accounts(**query) }
64
+ end
65
+
66
+ # 404 bank_connect.account.not_found for an unknown account.
67
+ def get_account(account_id)
68
+ read("/accounts/#{segment(account_id, 'accountId')}")
69
+ end
70
+
71
+ # Asks for a fresh read of the account from the bank (HTTP 202). It never reads earlier than the
72
+ # bank's minimum interval: the answer is then SCHEDULED with scheduledAt, and a request while one is
73
+ # waiting joins it. Nothing is written, so no Idempotency-Key. New transactions arrive by the
74
+ # bank_account.transaction.received webhook. 409 bank_connect.connection.not_active when the
75
+ # connection is not ACTIVE or DEGRADED; 429 RATE_LIMITED (RateLimitError, retry_after in seconds).
76
+ def request_sync(account_id)
77
+ RouteResponse.unwrap(@client.request('POST', "#{BASE}/accounts/#{segment(account_id, 'accountId')}/sync"))
78
+ end
79
+
80
+ # The latest balance of each account (bank-connect:transactions:view). Without accountId, every active
81
+ # account of the key's environment.
82
+ def list_balances(**filters)
83
+ page('/balances', 'listBalances', filters)
84
+ end
85
+
86
+ def iterate_balances(**filters, &block)
87
+ RouteResponse.each_item(filters, block) { |query| list_balances(**query) }
88
+ end
89
+
90
+ # Transactions, newest recorded first (receivedAt, which never changes, so paging forward never
91
+ # skips a transaction that arrives late with an older bank date). bookedFrom (inclusive) / bookedTo
92
+ # (exclusive) filter on the bank date: a Time or an ISO 8601 string with a time zone, at most 92 days
93
+ # apart; bookedTo needs bookedFrom (bookedFrom alone runs up to now). minAmountMinor / maxAmountMinor
94
+ # are inclusive minor-unit strings.
95
+ def list_transactions(**filters)
96
+ page('/transactions', 'listTransactions', filters)
97
+ end
98
+
99
+ def iterate_transactions(**filters, &block)
100
+ RouteResponse.each_item(filters, block) { |query| list_transactions(**query) }
101
+ end
102
+
103
+ # One transaction with its detail fields (balanceAfterMinor, documentNo, bank).
104
+ def get_transaction(transaction_id)
105
+ read("/transactions/#{segment(transaction_id, 'transactionId')}")
106
+ end
107
+
108
+ def inspect
109
+ '#<Lunixi::BankConnect>'
110
+ end
111
+
112
+ private
113
+
114
+ def page(path, route, filters)
115
+ RouteResponse.page(@client.request('GET', BASE + path, query: BankConnectFilters.read_query!(filters, route)))
116
+ end
117
+
118
+ def read(path)
119
+ RouteResponse.unwrap(@client.request('GET', BASE + path))
120
+ end
121
+
122
+ def segment(value, field)
123
+ RouteRequest.path!(":#{field}", field => value)
124
+ end
125
+ end
126
+
127
+ # bank_connect.transfers: outgoing transfers from a connected account (/api/v1/bank-connect/transfers).
128
+ #
129
+ # Every route, reads included, is signed and needs bank-connect:transfer; the key must have an IP
130
+ # allowlist and the request must come from a listed IP (403 bank_connect.auth.ip_allowlist_required /
131
+ # ip_not_allowed). With an API key there is no e-mail code: create answers SUBMITTED and the transfer
132
+ # is queued for the bank. Follow it with get or the bank_transfer.* webhooks. The bank chooses the rail;
133
+ # Lunixi does not check the balance.
134
+ class BankConnectTransfers
135
+ def initialize(invoker)
136
+ @invoker = invoker
137
+ end
138
+
139
+ # Payment purpose codes the bank accepts on this connection: { items: [{ code, name, order }] }. Pass
140
+ # one as paymentPurpose to create; leave it out for the bank's default.
141
+ def list_purposes(connection_id)
142
+ @invoker.data('listTransferPurposes', query: { 'connectionId' => RouteValue.text!(connection_id, 'connectionId') })
143
+ end
144
+
145
+ # Creates an outgoing transfer (HTTP 201): { transfer, stepUp, replayed }. request: accountId,
146
+ # receiverIban (TR IBAN, at most 42 characters), receiverName (2–140 characters), amountMinor (a
147
+ # positive minor-unit string: "150075" = 1,500.75 TRY), optional currency, paymentPurpose and
148
+ # description (at most 140 characters).
149
+ #
150
+ # idempotency_key (8–200 printable ASCII) is generated (UUID v4) when nil; a network error or a 5xx
151
+ # is retried with the same key and body. Keep your own key (e.g. your payout id) to retry safely
152
+ # across processes: the same key and body answer the existing transfer with replayed: true, another
153
+ # body is 409 bank_connect.transfer.idempotency_conflict. The key used is in transfer.idempotencyKey
154
+ # and on ApiError#idempotency_key.
155
+ def create(request, idempotency_key: nil)
156
+ body = @invoker.body!('createTransfer', request)
157
+ BankTransferInvoker.check_transfer!(body)
158
+ @invoker.keyed('createTransfer', body, idempotency_key)
159
+ end
160
+
161
+ # Transfers, newest first. Filters: accountId, status (one or an Array of BankTransferStatus),
162
+ # createdFrom (inclusive) / createdTo (exclusive) as a Time or an ISO 8601 string, limit 1–100, cursor.
163
+ def list(**filters)
164
+ @invoker.page('listTransfers', query: BankConnectFilters.transfer_query!(filters, 'listTransfers'))
165
+ end
166
+
167
+ def iterate(**filters, &block)
168
+ RouteResponse.each_item(filters, block) { |query| list(**query) }
169
+ end
170
+
171
+ # 404 bank_connect.transfer.not_found for an unknown id.
172
+ def get(transfer_id)
173
+ @invoker.data('getTransfer', params: { 'transferId' => transfer_id })
174
+ end
175
+
176
+ def inspect
177
+ '#<Lunixi::BankConnectTransfers>'
178
+ end
179
+ end
180
+
181
+ # bank_connect.fx: currency exchange between two active accounts of one connection in different
182
+ # currencies (/api/v1/bank-connect/fx). Same scope and IP allowlist rule as transfers.
183
+ #
184
+ # Flow: list_rates (optional), create_quote, then create_order with the quote id before
185
+ # quote.expiresAt (the bank sets the validity; see validForSeconds). The order is SUBMITTED and queued;
186
+ # follow it with get_order. Exchange orders have no webhook.
187
+ class BankConnectFx
188
+ def initialize(invoker)
189
+ @invoker = invoker
190
+ end
191
+
192
+ # Current rates on the connection: { items, refreshSeconds, fetchedAt }; rates are decimal strings.
193
+ def list_rates(connection_id)
194
+ @invoker.data('listFxRates', query: { 'connectionId' => RouteValue.text!(connection_id, 'connectionId') })
195
+ end
196
+
197
+ # Quotes an exchange (HTTP 201). request: sourceAccountId (you sell from it), targetAccountId (you buy
198
+ # into it) and exactly one of sourceAmountMinor / targetAmountMinor (a positive minor-unit string of
199
+ # that account's currency). Nothing is booked; a quote is used by one order.
200
+ def create_quote(request)
201
+ body = @invoker.body!('createFxQuote', request)
202
+ if body.key?('sourceAmountMinor') == body.key?('targetAmountMinor')
203
+ raise ConfigurationError, 'createFxQuote takes exactly one of sourceAmountMinor and targetAmountMinor.'
204
+ end
205
+ raise ConfigurationError, 'createFxQuote needs two different accounts.' if body['sourceAccountId'] == body['targetAccountId']
206
+
207
+ @invoker.post('createFxQuote', body)
208
+ end
209
+
210
+ # Executes a quote (HTTP 201): { order, replayed }. request: quoteId, optional description (at most
211
+ # 140 characters). idempotency_key follows the rule of transfers.create and is generated when nil.
212
+ # 409 bank_connect.fx.quote_expired / quote_used: ask for a new quote.
213
+ def create_order(request, idempotency_key: nil)
214
+ body = @invoker.body!('createFxOrder', request)
215
+ BankTransferInvoker.check_description!(body['description']) if body.key?('description')
216
+ @invoker.keyed('createFxOrder', body, idempotency_key)
217
+ end
218
+
219
+ # Exchange orders, newest first. Filters: status (one or an Array of BankFxOrderStatus), limit, cursor.
220
+ def list_orders(**filters)
221
+ @invoker.page('listFxOrders', query: BankConnectFilters.transfer_query!(filters, 'listFxOrders'))
222
+ end
223
+
224
+ def iterate_orders(**filters, &block)
225
+ RouteResponse.each_item(filters, block) { |query| list_orders(**query) }
226
+ end
227
+
228
+ # 404 bank_connect.fx.order_not_found for an unknown id.
229
+ def get_order(order_id)
230
+ @invoker.data('getFxOrder', params: { 'orderId' => order_id })
231
+ end
232
+
233
+ def inspect
234
+ '#<Lunixi::BankConnectFx>'
235
+ end
236
+ end
237
+
238
+ # Sends one route of BANK_TRANSFER_ROUTES, signed. The keyed writes (createTransfer, createFxOrder)
239
+ # take the caller's key (checked) or a new UUID v4, and are retried with the same key and body after
240
+ # a network error or a 5xx. Not a public API.
241
+ class BankTransferInvoker
242
+ def self.check_transfer!(body)
243
+ raise ConfigurationError, "'receiverIban' must be at most #{BANK_TRANSFER_IBAN_MAX} characters." if body['receiverIban'].length > BANK_TRANSFER_IBAN_MAX
244
+ unless body['receiverName'].length.between?(BANK_TRANSFER_RECEIVER_NAME_MIN, BANK_TRANSFER_RECEIVER_NAME_MAX)
245
+ raise ConfigurationError, "'receiverName' must be #{BANK_TRANSFER_RECEIVER_NAME_MIN}-#{BANK_TRANSFER_RECEIVER_NAME_MAX} characters."
246
+ end
247
+
248
+ body['currency'] = RouteValue.currency!(body['currency'], 'currency') if body.key?('currency')
249
+ if body.key?('paymentPurpose') && !(body['paymentPurpose'].is_a?(String) && body['paymentPurpose'].match?(BANK_TRANSFER_PAYMENT_PURPOSE_PATTERN))
250
+ raise ConfigurationError, "'paymentPurpose' must be a code from list_purposes (letters, digits, underscore; at most 64)."
251
+ end
252
+
253
+ check_description!(body['description']) if body.key?('description')
254
+ body
255
+ end
256
+
257
+ def self.check_description!(value)
258
+ return if value.is_a?(String) && value.length <= BANK_TRANSFER_DESCRIPTION_MAX
259
+
260
+ raise ConfigurationError, "'description' must be a string of at most #{BANK_TRANSFER_DESCRIPTION_MAX} characters."
261
+ end
262
+
263
+ # The caller's key (checked) or a new UUID v4 for nil / ''.
264
+ def self.idempotency_key_for(key)
265
+ return SecureRandom.uuid if key.nil? || key == ''
266
+
267
+ RouteRequest.printable_idempotency_key!(key)
268
+ end
269
+
270
+ def initialize(client, max_retries:, backoff:)
271
+ @client = client
272
+ @max_retries = max_retries
273
+ @backoff = backoff
274
+ end
275
+
276
+ # The body of a write route: unknown or missing fields fail before sending; nil and '' are left out;
277
+ # amounts are positive canonical minor-unit strings; other required fields non-empty strings (trimmed).
278
+ def body!(name, request)
279
+ route = BANK_TRANSFER_ROUTES.fetch(name)
280
+ given = RouteRequest.wire_keys!(request, route['required'] + route['optional'], name)
281
+ body = given.reject { |_, value| value == '' }
282
+ body.each_key { |key| body[key] = amount!(key, body[key]) if BANK_TRANSFER_AMOUNT_FIELDS.include?(key) }
283
+ missing = route['required'].reject { |key| body.key?(key) }
284
+ raise ConfigurationError, "#{name} requires #{missing.join(', ')}." unless missing.empty?
285
+
286
+ route['required'].each { |key| body[key] = RouteValue.text!(body[key], key) unless BANK_TRANSFER_AMOUNT_FIELDS.include?(key) }
287
+ body
288
+ end
289
+
290
+ def data(name, params: {}, query: {})
291
+ route = BANK_TRANSFER_ROUTES.fetch(name)
292
+ RouteResponse.unwrap(@client.request(route['method'], RouteRequest.path!(route['path'], params), query: query))
293
+ end
294
+
295
+ def page(name, query:)
296
+ route = BANK_TRANSFER_ROUTES.fetch(name)
297
+ RouteResponse.page(@client.request(route['method'], route['path'], query: query))
298
+ end
299
+
300
+ def post(name, body)
301
+ RouteResponse.unwrap(@client.request('POST', BANK_TRANSFER_ROUTES.fetch(name)['path'], body: body))
302
+ end
303
+
304
+ # 1 + max_retries attempts with the same key and body; a network error or a 5xx is retried, anything
305
+ # else is raised at once. An answered error carries the key as idempotency_key.
306
+ def keyed(name, body, idempotency_key)
307
+ key = self.class.idempotency_key_for(idempotency_key)
308
+ path = BANK_TRANSFER_ROUTES.fetch(name)['path']
309
+ attempt = 0
310
+ begin
311
+ RouteResponse.unwrap(@client.request('POST', path, body: body, idempotency_key: key, max_retries: 0))
312
+ rescue TransportError, ApiError => e
313
+ raise with_key(e, key), cause: nil unless retryable?(e) && attempt < @max_retries
314
+
315
+ @backoff.call(attempt)
316
+ attempt += 1
317
+ retry
318
+ end
319
+ end
320
+
321
+ private
322
+
323
+ def amount!(key, value)
324
+ Money.minor(value, positive: true)
325
+ rescue ConfigurationError
326
+ raise ConfigurationError, "'#{key}' must be a positive canonical minor-unit string such as \"150075\" (not a number).", cause: nil
327
+ end
328
+
329
+ def retryable?(error)
330
+ error.is_a?(TransportError) || error.status.to_i >= 500
331
+ end
332
+
333
+ def with_key(error, key)
334
+ return error unless error.is_a?(ApiError)
335
+
336
+ error.class.new(status: error.status, code: error.code, request_id: error.request_id, retry_after: error.retry_after,
337
+ details: error.details, idempotency_key: key, message: error.message)
338
+ end
339
+ end
340
+ end
@@ -0,0 +1,114 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Local checks of the bank-connect read filters (BANK_CONNECT_FILTERS) and of the transfer and FX list
5
+ # filters (BANK_TRANSFER_ROUTES query lists). Not a public API.
6
+ module BankConnectFilters
7
+ DAY_SECONDS = 24 * 60 * 60
8
+ AMOUNT_FILTERS = %w[minAmountMinor maxAmountMinor].freeze
9
+
10
+ module_function
11
+
12
+ # The query of a read route: unknown filters, values outside their set, limit outside 1–100, more
13
+ # than 100 account ids, a malformed amount or date window raise ConfigurationError. nil, '' and []
14
+ # are left out; a list (status of connections, canonicalType, accountId) is sent comma-separated.
15
+ def read_query!(filters, route)
16
+ given = RouteRequest.wire_keys!(filters || {}, BANK_CONNECT_FILTERS.fetch(route), 'bank-connect', 'filter')
17
+ query = given.each_with_object({}) do |(key, value), out|
18
+ out[key] = read_value(key, value, route) if RouteRequest.present?(value)
19
+ end
20
+ check_transaction_window!(query) if route == 'listTransactions'
21
+ query
22
+ end
23
+
24
+ # The query of listTransfers / listFxOrders.
25
+ def transfer_query!(filters, route)
26
+ given = RouteRequest.wire_keys!(filters || {}, BANK_TRANSFER_ROUTES.fetch(route)['query'], 'bank-connect transfer', 'filter')
27
+ given.each_with_object({}) do |(key, value), out|
28
+ out[key] = transfer_value(key, value, route) if RouteRequest.present?(value)
29
+ end
30
+ end
31
+
32
+ def read_value(key, value, route)
33
+ case key
34
+ when 'limit', 'cursor' then page_value(key, value)
35
+ when 'status' then route == 'listAccounts' ? one_of(key, value, BankAccountStatus::ALL) : list_of(key, value, BankConnectionStatus::ALL)
36
+ when 'direction' then one_of(key, value, BankTransactionDirection::ALL)
37
+ when 'canonicalType' then list_of(key, value, BankTransactionType::ALL)
38
+ when 'accountId' then account_ids(value)
39
+ when 'bankId', 'connectionId' then RouteValue.text!(value, key)
40
+ when 'currency' then RouteValue.currency!(value, key)
41
+ when 'bookedFrom', 'bookedTo' then RouteValue.iso_time!(value, key)
42
+ else amount(key, value)
43
+ end
44
+ end
45
+
46
+ def transfer_value(key, value, route)
47
+ case key
48
+ when 'limit', 'cursor' then page_value(key, value)
49
+ when 'status' then list_of(key, value, route == 'listFxOrders' ? BankFxOrderStatus::ALL : BankTransferStatus::ALL)
50
+ when 'accountId' then RouteValue.text!(value, key)
51
+ else RouteValue.iso_time!(value, key)
52
+ end
53
+ end
54
+
55
+ def page_value(key, value)
56
+ if key == 'limit'
57
+ unless value.is_a?(Integer) && value.between?(1, BANK_CONNECT_MAX_LIMIT)
58
+ raise ConfigurationError, "'limit' must be an integer from 1 to #{BANK_CONNECT_MAX_LIMIT}."
59
+ end
60
+ elsif !value.is_a?(String) || value.length > BANK_CONNECT_CURSOR_MAX_LENGTH
61
+ raise ConfigurationError, "'cursor' must be the next_cursor of the previous page, passed back unchanged."
62
+ end
63
+ value
64
+ end
65
+
66
+ def one_of(key, value, allowed)
67
+ raise ConfigurationError, "'#{key}' must be one of #{allowed.join(', ')}." unless value.is_a?(String) && allowed.include?(value)
68
+
69
+ value
70
+ end
71
+
72
+ def list_of(key, value, allowed)
73
+ Array(value).each { |entry| one_of(key, entry, allowed) }.join(',')
74
+ end
75
+
76
+ def account_ids(value)
77
+ ids = Array(value)
78
+ raise ConfigurationError, "'accountId' takes at most #{BANK_CONNECT_MAX_ACCOUNT_FILTER} account ids." if ids.length > BANK_CONNECT_MAX_ACCOUNT_FILTER
79
+
80
+ ids.map do |id|
81
+ raise ConfigurationError, "'accountId' must be account ids (strings without commas)." unless id.is_a?(String) && !id.strip.empty? && !id.include?(',')
82
+
83
+ id.strip
84
+ end.join(',')
85
+ end
86
+
87
+ # Amount filters are inclusive canonical minor-unit strings ("0" allowed).
88
+ def amount(key, value)
89
+ Money.minor(value, positive: false)
90
+ rescue ConfigurationError
91
+ raise ConfigurationError, "'#{key}' must be a canonical minor-unit string such as \"10000\" (not a number).", cause: nil
92
+ end
93
+
94
+ # bookedTo needs bookedFrom; when both are readable bookedFrom <= bookedTo and at most 92 days apart;
95
+ # minAmountMinor <= maxAmountMinor.
96
+ def check_transaction_window!(query)
97
+ raise ConfigurationError, "'bookedTo' needs 'bookedFrom': a window without a start is unbounded." if query.key?('bookedTo') && !query.key?('bookedFrom')
98
+
99
+ from = RouteValue.instant(query['bookedFrom'])
100
+ to = RouteValue.instant(query['bookedTo'])
101
+ if from && to
102
+ raise ConfigurationError, "'bookedFrom' must not be after 'bookedTo'." if from > to
103
+ if to - from > BANK_CONNECT_BOOKED_RANGE_MAX_DAYS * DAY_SECONDS
104
+ raise ConfigurationError, "'bookedFrom' and 'bookedTo' may be at most #{BANK_CONNECT_BOOKED_RANGE_MAX_DAYS} days apart. " \
105
+ 'Page through narrower windows.'
106
+ end
107
+ end
108
+ return unless query.key?('minAmountMinor') && query.key?('maxAmountMinor')
109
+ return unless query['minAmountMinor'].to_i > query['maxAmountMinor'].to_i
110
+
111
+ raise ConfigurationError, "'minAmountMinor' must not be greater than 'maxAmountMinor'."
112
+ end
113
+ end
114
+ end
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Bank accounts (/api/v1/bank-connect, product BANK_CONNECT): value sets, filters, the transfer and FX
5
+ # routes and the webhook events.
6
+
7
+ # Status of a bank connection. Data is read only while a connection is ACTIVE or DEGRADED (DEGRADED:
8
+ # the last reads from the bank failed, so the data may be older; see the account's freshness).
9
+ module BankConnectionStatus
10
+ PENDING_DOCUMENTS = 'PENDING_DOCUMENTS'
11
+ UNDER_REVIEW = 'UNDER_REVIEW'
12
+ PENDING_SETUP = 'PENDING_SETUP'
13
+ ACTIVE = 'ACTIVE'
14
+ DEGRADED = 'DEGRADED'
15
+ SUSPENDED = 'SUSPENDED'
16
+ DISCONNECTED = 'DISCONNECTED'
17
+ ALL = [PENDING_DOCUMENTS, UNDER_REVIEW, PENDING_SETUP, ACTIVE, DEGRADED, SUSPENDED, DISCONNECTED].freeze
18
+ end
19
+
20
+ module BankAccountStatus
21
+ ACTIVE = 'ACTIVE'
22
+ INACTIVE = 'INACTIVE'
23
+ ALL = [ACTIVE, INACTIVE].freeze
24
+ end
25
+
26
+ # Money in (CREDIT) or out (DEBIT). amountMinor is always positive.
27
+ module BankTransactionDirection
28
+ CREDIT = 'CREDIT'
29
+ DEBIT = 'DEBIT'
30
+ ALL = [CREDIT, DEBIT].freeze
31
+ end
32
+
33
+ # The bank-independent transaction type (canonicalType).
34
+ module BankTransactionType
35
+ TRANSFER_IN = 'TRANSFER_IN'
36
+ TRANSFER_OUT = 'TRANSFER_OUT'
37
+ INTERNAL_IN = 'INTERNAL_IN'
38
+ INTERNAL_OUT = 'INTERNAL_OUT'
39
+ POS_SETTLEMENT = 'POS_SETTLEMENT'
40
+ POS_SETTLEMENT_REFUND = 'POS_SETTLEMENT_REFUND'
41
+ FEE = 'FEE'
42
+ TAX = 'TAX'
43
+ CASH_IN = 'CASH_IN'
44
+ CASH_OUT = 'CASH_OUT'
45
+ CARD = 'CARD'
46
+ LOAN = 'LOAN'
47
+ FX = 'FX'
48
+ INTEREST = 'INTEREST'
49
+ OTHER = 'OTHER'
50
+ ALL = [TRANSFER_IN, TRANSFER_OUT, INTERNAL_IN, INTERNAL_OUT, POS_SETTLEMENT, POS_SETTLEMENT_REFUND, FEE, TAX, CASH_IN, CASH_OUT,
51
+ CARD, LOAN, FX, INTEREST, OTHER].freeze
52
+ end
53
+
54
+ # AVAILABLE: the bank can be connected (connections are started in the Lunixi dashboard).
55
+ module BankAvailability
56
+ AVAILABLE = 'AVAILABLE'
57
+ COMING_SOON = 'COMING_SOON'
58
+ ALL = [AVAILABLE, COMING_SOON].freeze
59
+ end
60
+
61
+ # What a bank or a connection offers. OUTGOING_TRANSFER and FX_EXCHANGE open bank_connect.transfers and
62
+ # bank_connect.fx.
63
+ module BankCapability
64
+ ACCOUNT_LIST = 'ACCOUNT_LIST'
65
+ BALANCE = 'BALANCE'
66
+ TRANSACTIONS = 'TRANSACTIONS'
67
+ OUTGOING_TRANSFER = 'OUTGOING_TRANSFER'
68
+ FX_EXCHANGE = 'FX_EXCHANGE'
69
+ ALL = [ACCOUNT_LIST, BALANCE, TRANSACTIONS, OUTGOING_TRANSFER, FX_EXCHANGE].freeze
70
+ end
71
+
72
+ # QUEUED: the read starts now or is already waiting. SCHEDULED: it runs at scheduledAt.
73
+ module BankSyncStatus
74
+ QUEUED = 'QUEUED'
75
+ SCHEDULED = 'SCHEDULED'
76
+ ALL = [QUEUED, SCHEDULED].freeze
77
+ end
78
+
79
+ # Bank-account webhook events (subscription bank_account.*). TRANSACTION_RECEIVED: a new transaction
80
+ # (CREDIT or DEBIT) was read from a connected account by a regular read after the connection became
81
+ # active; the history loaded when an account is first connected sends none. Read it with
82
+ # Lunixi::BankConnectWebhook.parse; the event id is the same on every redelivery.
83
+ module BankConnectEvents
84
+ TRANSACTION_RECEIVED = 'bank_account.transaction.received'
85
+ PATTERN = 'bank_account.*'
86
+ ALL = [TRANSACTION_RECEIVED].freeze
87
+ end
88
+
89
+ # Status of an outgoing transfer. PENDING_OTP: started in the dashboard, waiting for the user's code (an
90
+ # API-key transfer never has it). SUBMITTED: queued or sent to the bank. COMPLETED can still become
91
+ # RETURNED. FAILED, RETURNED and CANCELED are final.
92
+ module BankTransferStatus
93
+ PENDING_OTP = 'PENDING_OTP'
94
+ SUBMITTED = 'SUBMITTED'
95
+ PROCESSING = 'PROCESSING'
96
+ COMPLETED = 'COMPLETED'
97
+ FAILED = 'FAILED'
98
+ RETURNED = 'RETURNED'
99
+ CANCELED = 'CANCELED'
100
+ ALL = [PENDING_OTP, SUBMITTED, PROCESSING, COMPLETED, FAILED, RETURNED, CANCELED].freeze
101
+ end
102
+
103
+ # The rail the bank chose; UNKNOWN until it says.
104
+ module BankTransferRail
105
+ INTERNAL = 'INTERNAL'
106
+ INTRABANK = 'INTRABANK'
107
+ FAST = 'FAST'
108
+ EFT = 'EFT'
109
+ UNKNOWN = 'UNKNOWN'
110
+ ALL = [INTERNAL, INTRABANK, FAST, EFT, UNKNOWN].freeze
111
+ end
112
+
113
+ module BankTransferInitiatedVia
114
+ PANEL = 'PANEL'
115
+ API = 'API'
116
+ ALL = [PANEL, API].freeze
117
+ end
118
+
119
+ # Status of a currency exchange order; an order is created SUBMITTED.
120
+ module BankFxOrderStatus
121
+ SUBMITTED = 'SUBMITTED'
122
+ COMPLETED = 'COMPLETED'
123
+ FAILED = 'FAILED'
124
+ ALL = [SUBMITTED, COMPLETED, FAILED].freeze
125
+ end
126
+
127
+ # Which amount of a quote you fixed: SOURCE (sell amount) or TARGET (buy amount).
128
+ module BankFxRequestedSide
129
+ SOURCE = 'SOURCE'
130
+ TARGET = 'TARGET'
131
+ ALL = [SOURCE, TARGET].freeze
132
+ end
133
+
134
+ # Bank Connect transfer webhook events (subscription bank_transfer.*), one per transfer and type. Not
135
+ # the payment method's bank transfer events (payment.bank_transfer.*, Lunixi::PaymentBankTransferEvents).
136
+ # Exchange orders have no webhook.
137
+ module BankTransferEvents
138
+ CREATED = 'bank_transfer.created'
139
+ COMPLETED = 'bank_transfer.completed'
140
+ FAILED = 'bank_transfer.failed'
141
+ RETURNED = 'bank_transfer.returned'
142
+ PATTERN = 'bank_transfer.*'
143
+ ALL = [CREATED, COMPLETED, FAILED, RETURNED].freeze
144
+ end
145
+
146
+ # Query filters each read route accepts (the gateway rejects any other with 400).
147
+ BANK_CONNECT_FILTERS = {
148
+ 'listBanks' => %w[limit cursor].freeze,
149
+ 'listConnections' => %w[limit cursor status bankId].freeze,
150
+ 'listAccounts' => %w[limit cursor connectionId bankId currency status].freeze,
151
+ 'listBalances' => %w[limit cursor accountId currency].freeze,
152
+ 'listTransactions' => %w[limit cursor accountId bookedFrom bookedTo direction minAmountMinor maxAmountMinor canonicalType].freeze
153
+ }.freeze
154
+ # Largest page (limit 1–100; the gateway's default is 25).
155
+ BANK_CONNECT_MAX_LIMIT = 100
156
+ # Most account ids one accountId filter may carry.
157
+ BANK_CONNECT_MAX_ACCOUNT_FILTER = 100
158
+ # Widest bookedFrom … bookedTo window of one transaction request, in days.
159
+ BANK_CONNECT_BOOKED_RANGE_MAX_DAYS = 92
160
+ BANK_CONNECT_CURSOR_MAX_LENGTH = 2048
161
+
162
+ # Transfer and exchange routes: method, path, body fields, query fields and the Idempotency-Key rule.
163
+ # The same table as the Node SDK's BANK_TRANSFER_ROUTES (forbidNonWhitelisted: any other field is a
164
+ # 400); the parity test compares it with the shared catalog. Every route is signed and needs
165
+ # bank-connect:transfer plus a key with an IP allowlist.
166
+ BANK_TRANSFER_ROUTES = {
167
+ 'listTransferPurposes' => RouteRequest.route('GET', '/api/v1/bank-connect/transfer-purposes', idempotency_key: false, query: %w[connectionId]),
168
+ 'createTransfer' => RouteRequest.route('POST', '/api/v1/bank-connect/transfers',
169
+ idempotency_key: true, required: %w[accountId receiverIban receiverName amountMinor],
170
+ optional: %w[currency paymentPurpose description]),
171
+ 'listTransfers' => RouteRequest.route('GET', '/api/v1/bank-connect/transfers',
172
+ idempotency_key: false, query: %w[limit cursor accountId status createdFrom createdTo]),
173
+ 'getTransfer' => RouteRequest.route('GET', '/api/v1/bank-connect/transfers/:transferId', idempotency_key: false),
174
+ 'listFxRates' => RouteRequest.route('GET', '/api/v1/bank-connect/fx/rates', idempotency_key: false, query: %w[connectionId]),
175
+ 'createFxQuote' => RouteRequest.route('POST', '/api/v1/bank-connect/fx/quotes',
176
+ idempotency_key: false, required: %w[sourceAccountId targetAccountId],
177
+ optional: %w[sourceAmountMinor targetAmountMinor]),
178
+ 'createFxOrder' => RouteRequest.route('POST', '/api/v1/bank-connect/fx/orders', idempotency_key: true, required: %w[quoteId], optional: %w[description]),
179
+ 'listFxOrders' => RouteRequest.route('GET', '/api/v1/bank-connect/fx/orders', idempotency_key: false, query: %w[limit cursor status]),
180
+ 'getFxOrder' => RouteRequest.route('GET', '/api/v1/bank-connect/fx/orders/:orderId', idempotency_key: false)
181
+ }.freeze
182
+
183
+ # Idempotency-Key of create_transfer / create_order: 8–200 printable ASCII characters.
184
+ BANK_TRANSFER_IDEMPOTENCY_KEY_PATTERN = RouteRequest::PRINTABLE_IDEMPOTENCY_KEY
185
+ # paymentPurpose: a code from transfers.list_purposes.
186
+ BANK_TRANSFER_PAYMENT_PURPOSE_PATTERN = /\A[A-Za-z0-9_]{1,64}\z/
187
+ BANK_TRANSFER_DESCRIPTION_MAX = 140
188
+ BANK_TRANSFER_RECEIVER_NAME_MIN = 2
189
+ BANK_TRANSFER_RECEIVER_NAME_MAX = 140
190
+ # Longest receiverIban the gateway accepts (spaces included); the service checks the TR IBAN checksum.
191
+ BANK_TRANSFER_IBAN_MAX = 42
192
+ # Body fields that carry a minor-unit amount string.
193
+ BANK_TRANSFER_AMOUNT_FIELDS = %w[amountMinor sourceAmountMinor targetAmountMinor].freeze
194
+
195
+ # data fields of the bank_account.transaction.received webhook (values the bank did not send are nil).
196
+ BANK_ACCOUNT_TRANSACTION_RECEIVED_FIELDS = %w[
197
+ transactionId accountId connectionId bankEftCode bankName direction amountMinor currency bookedAt valueAt receivedAt
198
+ canonicalType description counterpartyNameMasked counterpartyIbanMasked receiptNo
199
+ ].freeze
200
+ # data fields of a bank_transfer.* webhook (values without a value are nil).
201
+ BANK_TRANSFER_WEBHOOK_FIELDS = %w[
202
+ transferId connectionId accountId bankEftCode bankName status rail amountMinor currency receiverIbanMasked receiverNameMasked
203
+ paymentPurpose description failureCode idempotencyKey createdAt completedAt failedAt returnedAt
204
+ ].freeze
205
+ end