lunixi-sdk 2.0.2 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +28 -0
  3. data/README.md +43 -4
  4. data/README.tr.md +28 -3
  5. data/docs/card-rewards.md +21 -0
  6. data/lib/lunixi/bank_connect.rb +132 -15
  7. data/lib/lunixi/bank_connect_filters.rb +13 -3
  8. data/lib/lunixi/bank_connect_pos.rb +165 -0
  9. data/lib/lunixi/bank_connect_values.rb +127 -5
  10. data/lib/lunixi/card_requests.rb +9 -1
  11. data/lib/lunixi/client.rb +38 -14
  12. data/lib/lunixi/direct_method_payment_request.rb +24 -2
  13. data/lib/lunixi/errors.rb +49 -0
  14. data/lib/lunixi/fraud.rb +3 -2
  15. data/lib/lunixi/fraud_uk_claims.rb +127 -0
  16. data/lib/lunixi/fraud_values.rb +46 -0
  17. data/lib/lunixi/marketplace.rb +2 -0
  18. data/lib/lunixi/payment_link_rules.rb +13 -1
  19. data/lib/lunixi/payment_link_values.rb +4 -0
  20. data/lib/lunixi/payment_links.rb +3 -1
  21. data/lib/lunixi/payment_values.rb +22 -2
  22. data/lib/lunixi/payments.rb +62 -6
  23. data/lib/lunixi/product_webhooks.rb +17 -1
  24. data/lib/lunixi/refund_to_wallet.rb +94 -0
  25. data/lib/lunixi/route_table.rb +10 -5
  26. data/lib/lunixi/routing_pin.rb +247 -0
  27. data/lib/lunixi/sanction.rb +77 -17
  28. data/lib/lunixi/sanction_batch.rb +215 -0
  29. data/lib/lunixi/sanction_values.rb +289 -5
  30. data/lib/lunixi/split_payment.rb +17 -2
  31. data/lib/lunixi/subscription_routing.rb +70 -0
  32. data/lib/lunixi/subscription_values.rb +26 -3
  33. data/lib/lunixi/subscriptions.rb +22 -2
  34. data/lib/lunixi/version.rb +1 -1
  35. data/lib/lunixi/wallet.rb +43 -7
  36. data/lib/lunixi/wallet_customer_sessions.rb +75 -0
  37. data/lib/lunixi/wallet_customer_tokens.rb +238 -0
  38. data/lib/lunixi/wallet_portal.rb +340 -0
  39. data/lib/lunixi/wallet_portal_routes.rb +171 -0
  40. data/lib/lunixi/wallet_routes.rb +28 -3
  41. data/lib/lunixi/wallet_rules.rb +131 -0
  42. data/lib/lunixi/wallet_values.rb +151 -0
  43. data/lib/lunixi.rb +12 -0
  44. metadata +14 -1
@@ -0,0 +1,247 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # routing.mode: what happens when the pinned provider or connection cannot take the payment.
5
+ # PREFER (the gateway's default) sends the first attempt to the target and routes the payment as
6
+ # usual when it cannot take it (routing.outcome FALLBACK with a reason). STRICT uses only the target:
7
+ # the gateway answers 422 payment.routing.pin_not_eligible before any bank call, and with a
8
+ # credentialId there is no failover to another connection. On a method other than card the provider
9
+ # pin is always strict (the method block's providerCode); mode then applies to the connection choice.
10
+ module RoutingPinMode
11
+ PREFER = 'PREFER'
12
+ STRICT = 'STRICT'
13
+
14
+ ALL = [PREFER, STRICT].freeze
15
+ end
16
+
17
+ # routing.outcome of a pinned payment's response, detail and webhooks, and of an installment
18
+ # quote's data.routing. In a quote with a STRICT pin whose target does not offer the installment the
19
+ # outcome is nil: the installment is answered as not offered (offered: false) and reason says why.
20
+ module RoutingPinOutcome
21
+ # The payment went to the pinned target.
22
+ APPLIED = 'APPLIED'
23
+ # PREFER only: the target could not take the payment; the platform routed it (see reason).
24
+ FALLBACK = 'FALLBACK'
25
+
26
+ ALL = [APPLIED, FALLBACK].freeze
27
+ end
28
+
29
+ # routing.reason of a FALLBACK and details.reason of 422 payment.routing.pin_not_eligible. The list
30
+ # may grow; treat an unknown value as "not eligible".
31
+ module RoutingPinReason
32
+ INACTIVE = 'INACTIVE'
33
+ MAINTENANCE = 'MAINTENANCE'
34
+ CAPACITY = 'CAPACITY'
35
+ ENVIRONMENT_MISMATCH = 'ENVIRONMENT_MISMATCH'
36
+ CURRENCY_NOT_SUPPORTED = 'CURRENCY_NOT_SUPPORTED'
37
+ AMOUNT_OUT_OF_RANGE = 'AMOUNT_OUT_OF_RANGE'
38
+ INSTALLMENT_NOT_AUTHORIZED = 'INSTALLMENT_NOT_AUTHORIZED'
39
+ THREE_DS_NOT_SUPPORTED = 'THREE_DS_NOT_SUPPORTED'
40
+ TWO_D_NOT_SUPPORTED = 'TWO_D_NOT_SUPPORTED'
41
+ BANK_NOT_ENABLED = 'BANK_NOT_ENABLED'
42
+ # A card reward selection is bound to another connection (PREFER: the pin is dropped).
43
+ REWARD_BINDING = 'REWARD_BINDING'
44
+
45
+ ALL = [INACTIVE, MAINTENANCE, CAPACITY, ENVIRONMENT_MISMATCH, CURRENCY_NOT_SUPPORTED, AMOUNT_OUT_OF_RANGE,
46
+ INSTALLMENT_NOT_AUTHORIZED, THREE_DS_NOT_SUPPORTED, TWO_D_NOT_SUPPORTED, BANK_NOT_ENABLED, REWARD_BINDING].freeze
47
+ end
48
+
49
+ # Error codes of the routing pin (ApiError#code).
50
+ module RoutingPinErrorCode
51
+ # 400: credentialId is not one of your connections.
52
+ CREDENTIAL_UNKNOWN = 'payment.routing.credential_unknown'
53
+ # 400: providerCode is not connected to your account (the same answer in STRICT and PREFER).
54
+ PROVIDER_NOT_CONNECTED = 'payment.routing.provider_not_connected'
55
+ # 400: the pin does not fit the request; details.mismatch is a RoutingPinMismatch value.
56
+ PIN_MISMATCH = 'payment.routing.pin_mismatch'
57
+ # 422 (STRICT): the target cannot take this payment; details.reason. Nothing was charged.
58
+ PIN_NOT_ELIGIBLE = 'payment.routing.pin_not_eligible'
59
+ # 422 (STRICT): the pin conflicts with a card reward selection bound to another connection.
60
+ PIN_CONFLICT = 'payment.routing.pin_conflict'
61
+ # 500: the payment could not be completed; nothing was charged. Retry later.
62
+ PIN_VIOLATION = 'payment.routing.pin_violation'
63
+ # 422: the installment quote was made with another pin (or without one).
64
+ INSTALLMENT_QUOTE_PIN_MISMATCH = 'installment.quote.pin_mismatch'
65
+ end
66
+
67
+ # details.mismatch of 400 payment.routing.pin_mismatch: what does not fit.
68
+ module RoutingPinMismatch
69
+ # The connection (credentialId) does not belong to routing.providerCode.
70
+ PROVIDER_CREDENTIAL = 'PROVIDER_CREDENTIAL'
71
+ # The method block's providerCode differs from routing.providerCode.
72
+ BLOCK_PROVIDER = 'BLOCK_PROVIDER'
73
+ # The target does not support this payment method (or none of the checkout's methods).
74
+ PAYMENT_METHOD = 'PAYMENT_METHOD'
75
+ # Payment link: the target has no connection in the link's environment (details.environment).
76
+ ENVIRONMENT = 'ENVIRONMENT'
77
+
78
+ ALL = [PROVIDER_CREDENTIAL, BLOCK_PROVIDER, PAYMENT_METHOD, ENVIRONMENT].freeze
79
+ end
80
+
81
+ # Fields of the routing request object; at least one of providerCode and credentialId is required.
82
+ ROUTING_PIN_FIELDS = %w[providerCode credentialId mode].freeze
83
+
84
+ # Fields of the routing result of a pinned payment.
85
+ ROUTING_PIN_RESULT_FIELDS = %w[requested outcome reason].freeze
86
+
87
+ # status of a connection in payments.connections.list (ACTIVE, MAINTENANCE, INACTIVE) and in the
88
+ # payment.connection.status_changed event (status, previousStatus; also DELETED).
89
+ module PaymentConnectionStatus
90
+ ACTIVE = 'ACTIVE'
91
+ # Listed so you can see why a STRICT pin to it answers 422.
92
+ MAINTENANCE = 'MAINTENANCE'
93
+ INACTIVE = 'INACTIVE'
94
+ # Only in the event: the connection was deleted. A deleted connection is not listed.
95
+ DELETED = 'DELETED'
96
+
97
+ ALL = [ACTIVE, MAINTENANCE, INACTIVE, DELETED].freeze
98
+ end
99
+
100
+ # environment of a connection.
101
+ module PaymentConnectionEnvironment
102
+ LIVE = 'LIVE'
103
+ TEST = 'TEST'
104
+
105
+ ALL = [LIVE, TEST].freeze
106
+ end
107
+
108
+ # Fields of one row of GET /payments/connections. Secrets and provider-side account numbers are
109
+ # never returned.
110
+ PAYMENT_CONNECTION_FIELDS = %w[credentialId providerCode providerName displayName paymentMethods environment status
111
+ supports2D supports3DS installment currencies].freeze
112
+
113
+ # Options of payments.connections.list.
114
+ LIST_PAYMENT_CONNECTIONS_OPTIONS = %w[paymentMethod].freeze
115
+
116
+ # Webhook event of a connection (one of the payment.* events): the status of a connection changed
117
+ # (put into or taken out of maintenance, deactivated, reactivated or deleted), so a STRICT
118
+ # integration learns about it before a payment is refused.
119
+ module PaymentConnectionEvents
120
+ STATUS_CHANGED = 'payment.connection.status_changed'
121
+
122
+ ALL = [STATUS_CHANGED].freeze
123
+ end
124
+
125
+ # Fields of the payment.connection.status_changed event data.
126
+ PAYMENT_CONNECTION_STATUS_CHANGED_FIELDS = %w[credentialId merchantId providerCode displayName environment status
127
+ previousStatus].freeze
128
+
129
+ # Checks of the routing pin, applied before any request is sent.
130
+ module RoutingPin
131
+ CREDENTIAL_ID_PATTERN = /\A[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\z/
132
+
133
+ module_function
134
+
135
+ # A routing Hash ({ providerCode:, credentialId:, mode: }, string or symbol keys) as a string-keyed
136
+ # copy with the given fields only. At least one of providerCode and credentialId is required;
137
+ # credentialId is a connection id (uuid) from payments.connections.list or the panel; mode is one of
138
+ # RoutingPinMode::ALL (left out = PREFER on the gateway). Whether the connection is yours and belongs
139
+ # to the provider is checked by the gateway.
140
+ def pin!(value, path = 'routing')
141
+ raise ConfigurationError, "#{path} must be a Hash such as { credentialId:, mode: 'STRICT' }" unless value.is_a?(Hash)
142
+
143
+ data = value.transform_keys(&:to_s)
144
+ unknown = data.keys - ROUTING_PIN_FIELDS
145
+ raise ConfigurationError, "Unknown #{path} field(s): #{unknown.join(', ')}; #{path} takes #{ROUTING_PIN_FIELDS.join(', ')}" unless unknown.empty?
146
+
147
+ pin = {}
148
+ pin['providerCode'] = MethodFields.provider_code!(data['providerCode']) unless data['providerCode'].nil?
149
+ unless data['credentialId'].nil?
150
+ credential = data['credentialId']
151
+ unless credential.is_a?(String) && credential.match?(CREDENTIAL_ID_PATTERN)
152
+ raise ConfigurationError, "#{path}.credentialId must be a connection id (uuid) from payments.connections.list"
153
+ end
154
+
155
+ pin['credentialId'] = credential
156
+ end
157
+ raise ConfigurationError, "#{path} needs providerCode, credentialId or both" if pin.empty?
158
+
159
+ unless data['mode'].nil?
160
+ raise ConfigurationError, "#{path}.mode must be PREFER or STRICT" unless RoutingPinMode::ALL.include?(data['mode'])
161
+
162
+ pin['mode'] = data['mode']
163
+ end
164
+ pin
165
+ end
166
+
167
+ # Checks body['routing'] of a string-keyed body when present and returns the body with the checked
168
+ # copy. With a method block that names a providerCode both codes must be equal; BANK_TRANSFER takes
169
+ # no routing.
170
+ def field!(body, path = 'routing', payment_method: nil, block_provider_code: nil)
171
+ return body unless body.is_a?(Hash) && body.key?('routing')
172
+ raise ConfigurationError, "#{path} must be a Hash; leave it out for no pin" if body['routing'].nil?
173
+
174
+ pin = pin!(body['routing'], path)
175
+ method = payment_method.nil? || payment_method == '' ? nil : MethodFields.normalize_payment_method(payment_method)
176
+ raise ConfigurationError, "paymentMethod BANK_TRANSFER takes no #{path}: the platform picks its single provider" if method == PaymentMethod::BANK_TRANSFER
177
+
178
+ if !block_provider_code.nil? && pin.key?('providerCode') && pin['providerCode'] != block_provider_code
179
+ raise ConfigurationError, "#{path}.providerCode (#{pin['providerCode']}) must equal the method block's providerCode (#{block_provider_code})"
180
+ end
181
+
182
+ body['routing'] = pin
183
+ body
184
+ end
185
+
186
+ # The routing result of a payment response, detail or installment quote ({ 'requested', 'outcome',
187
+ # 'reason' }), or nil when the request carried no pin. An unknown reason is passed through as it is.
188
+ def result(response)
189
+ data = response.is_a?(Hash) && response.key?('data') ? response['data'] : response
190
+ routing = data.is_a?(Hash) ? data['routing'] : nil
191
+ routing.is_a?(Hash) ? routing : nil
192
+ end
193
+ end
194
+
195
+ # Your payment provider connections (payments.connections): the accounts a payment can be pinned to
196
+ # with routing.credentialId. Call it when you set up your integration, not before each payment: a
197
+ # connection's credentialId does not change for its lifetime, so keep it in your configuration. A pin
198
+ # with providerCode only needs no listing.
199
+ class PaymentConnections
200
+ PATH = '/api/v1/payments/connections'
201
+
202
+ def initialize(client)
203
+ @client = client
204
+ end
205
+
206
+ # GET /payments/connections (signed, server only). data.connections[]: PAYMENT_CONNECTION_FIELDS,
207
+ # ordered by providerCode, then displayName; connections in maintenance and inactive ones are
208
+ # listed too, deleted ones are not. payment_method lists the connections of that method only (QR is
209
+ # sent as QR_CODE); an unknown code is a 400 payment.method.unknown.
210
+ def list(payment_method: nil)
211
+ query = payment_method.nil? ? {} : { paymentMethod: MethodFields.normalize_payment_method(payment_method) }
212
+ @client.request('GET', PATH, query: query)
213
+ end
214
+ end
215
+
216
+ # The connection of a verified payment.connection.status_changed webhook
217
+ # (PAYMENT_CONNECTION_STATUS_CHANGED_FIELDS); raw keeps the whole data. status is the new
218
+ # PaymentConnectionStatus (DELETED when the connection was deleted), previous_status the one before.
219
+ class PaymentConnectionStatusChanged
220
+ attr_reader :credential_id, :merchant_id, :provider_code, :display_name, :environment, :status,
221
+ :previous_status, :raw
222
+
223
+ # event_type and data of the verified event; another type raises ConfigurationError.
224
+ def self.from_event(event_type, data)
225
+ unless event_type == PaymentConnectionEvents::STATUS_CHANGED
226
+ raise ConfigurationError, "Expected a '#{PaymentConnectionEvents::STATUS_CHANGED}' event, got '#{event_type}'"
227
+ end
228
+
229
+ new(data.is_a?(Hash) ? data.transform_keys(&:to_s) : {})
230
+ end
231
+
232
+ def initialize(data)
233
+ @raw = data.freeze
234
+ @credential_id = data['credentialId'].to_s
235
+ @merchant_id = data['merchantId'].to_s
236
+ @provider_code = data['providerCode'].to_s
237
+ @display_name = data['displayName'].to_s
238
+ @environment = data['environment'].to_s
239
+ @status = data['status'].to_s
240
+ @previous_status = data['previousStatus'].to_s
241
+ end
242
+
243
+ def deleted?
244
+ status == PaymentConnectionStatus::DELETED
245
+ end
246
+ end
247
+ end
@@ -17,8 +17,25 @@ module Lunixi
17
17
  #
18
18
  # Answers are the envelope's data. The envelope's requestId is the HTTP request's id; the screening's
19
19
  # own id is data.screeningRequestId (name screening). Lists return a Lunixi::ListPage.
20
+ #
21
+ # Bulk screening (/api/v1/sanction/batches): writes need sanction:batch_screen and actor_id, sent as
22
+ # X-Actor-Id (the person in your organization acting; required with an API key); reads need
23
+ # sanction:batch_view. Heavy writes may answer 503 sanction.batch.capacity_busy with Retry-After.
20
24
  class Sanction
21
25
  BLOCKING_DECISIONS = %w[block blocked reject rejected review hit escalate].freeze
26
+ ACTOR_ID = /\A[A-Za-z0-9._@+-]{1,64}\z/
27
+ # The optional Idempotency-Key of a screening: 8–120 printable ASCII characters without spaces.
28
+ SCREENING_KEY = /\A[\x21-\x7E]{8,120}\z/
29
+ # The screenings that take it (the transport applies the same format there).
30
+ SCREENING_ROUTE = %r{\A/api/v1/sanction/(?:screening/|intelligence/public-procurement-ban(?:\?|\z))}
31
+
32
+ # Checks the optional Idempotency-Key of a screening; returns it.
33
+ def self.screening_key!(key)
34
+ return key if key.is_a?(String) && key.match?(SCREENING_KEY)
35
+
36
+ raise ConfigurationError, 'idempotency_key of a screening must be 8-120 printable ASCII characters without spaces.'
37
+ end
38
+ include SanctionBatch
22
39
 
23
40
  # Whether a screening answer (the data a screen_* method returned) can be read as "nothing found":
24
41
  # no match or hit of any kind, no listed or blocking flag, no blocking decision, and, when it reports
@@ -34,35 +51,52 @@ module Lunixi
34
51
  true
35
52
  end
36
53
 
37
- def initialize(client)
54
+ def initialize(client, storage_transport: nil)
38
55
  @client = client
56
+ @storage_transport = storage_transport
39
57
  end
40
58
 
41
59
  # Person or organization: { name, subjectType?, country?, dateOfBirth?, identifiers?, riskDomains?,
42
- # mode?, threshold?, customerReference? }.
43
- def screen_name(request)
44
- screening('screenName', request)
60
+ # mode?, threshold?, customerReference?, nationality?, residenceCountry?, registrationCountry? }.
61
+ #
62
+ # nationality and residenceCountry (a person) and registrationCountry (an organization) are
63
+ # ISO 3166-1 alpha-2 codes read only by the country risk lists, never by name matching; the answer's
64
+ # jurisdictionRisk reports them. A field that does not apply to the subject type is refused with 400 sanction.screen_name.failed,
65
+ # details.issues[].code FIELD_NOT_APPLICABLE_FOR_SUBJECT_TYPE; an invalid code likewise (NATIONALITY_INVALID,
66
+ # RESIDENCE_COUNTRY_INVALID, REGISTRATION_COUNTRY_INVALID). A country on the FATF call-for-action
67
+ # list turns an allow into a review (REVIEW_HIGH_RISK_JURISDICTION); a country never blocks.
68
+ def screen_name(request = nil, idempotency_key: nil, **fields)
69
+ screening('screenName', keyed_body(request, fields), idempotency_key)
45
70
  end
46
71
 
47
72
  # Crypto wallet address (exact match against the listed addresses).
48
- def screen_wallet(request)
49
- screening('screenWallet', request)
73
+ def screen_wallet(request = nil, idempotency_key: nil, **fields)
74
+ screening('screenWallet', keyed_body(request, fields), idempotency_key)
75
+ end
76
+
77
+ # Website or host against the websites of the active list publication: { website, customerReference? }
78
+ # (website: a URL or host, at most 2048 characters). The host is compared in canonical form (lower
79
+ # case, punycode, no www., port or path): a hit is the listed host itself (EXACT_HOST) or a subdomain
80
+ # of it (PARENT_DOMAIN). The answer carries screeningRequestId, website, domain, matched, riskScore,
81
+ # decision (review or allow, never a block), hits and the publication evidence.
82
+ def screen_website(request = nil, idempotency_key: nil, **fields)
83
+ screening('screenWebsite', keyed_body(request, fields), idempotency_key)
50
84
  end
51
85
 
52
86
  # Bank account / IBAN against your own deny list and account risk data (no list publication).
53
- def screen_account(request)
54
- screening('screenAccount', request)
87
+ def screen_account(request = nil, idempotency_key: nil, **fields)
88
+ screening('screenAccount', keyed_body(request, fields), idempotency_key)
55
89
  end
56
90
 
57
91
  # Every party and account of a transaction, against one list publication.
58
- def screen_transaction(request)
59
- screening('screenTransaction', request)
92
+ def screen_transaction(request = nil, idempotency_key: nil, **fields)
93
+ screening('screenTransaction', keyed_body(request, fields), idempotency_key)
60
94
  end
61
95
 
62
96
  # Public procurement debarment lists, by name and TCKN / VKN. A list that is not published makes
63
97
  # coverageStatus PARTIAL and is named in uncoveredSources: no match is not a clean result for it.
64
- def screen_public_procurement_ban(request)
65
- screening('screenPublicProcurementBan', request)
98
+ def screen_public_procurement_ban(request = nil, idempotency_key: nil, **fields)
99
+ screening('screenPublicProcurementBan', keyed_body(request, fields), idempotency_key)
66
100
  end
67
101
 
68
102
  # Adverse media. Runs only when your adverse-media policy is enabled.
@@ -174,8 +208,11 @@ module Lunixi
174
208
 
175
209
  private
176
210
 
177
- def screening(name, request)
178
- checked(invoke(name, body: request))
211
+ # idempotency_key: the optional Idempotency-Key of the name, wallet, website, account and public
212
+ # procurement ban screenings (8–120 printable ASCII characters; the gateway answers 400
213
+ # sanction.idempotency_key.invalid otherwise). Nothing is sent without it.
214
+ def screening(name, request, idempotency_key = nil)
215
+ checked(invoke(name, body: request, idempotency_key: idempotency_key))
179
216
  end
180
217
 
181
218
  def page(name, filters)
@@ -186,13 +223,36 @@ module Lunixi
186
223
  RouteResponse.unwrap(invoke(name, params: { 'entityId' => entity_id }, query: RouteRequest.compact(query)))
187
224
  end
188
225
 
189
- # Sends one route of SANCTION_ROUTES with the access token (no request signature).
190
- def invoke(name, params: {}, body: nil, query: nil)
226
+ # Sends one route of SANCTION_ROUTES with the access token (no request signature); X-Actor-Id and the
227
+ # Idempotency-Key go only to the routes that take them.
228
+ def invoke(name, params: {}, body: nil, query: nil, actor_id: nil, idempotency_key: nil)
191
229
  route = SANCTION_ROUTES.fetch(name)
230
+ actor = route['actorId'] ? actor!(actor_id) : nil
231
+ key = if route['idempotencyKey'] then batch_key!(idempotency_key)
232
+ elsif !idempotency_key.nil? then Sanction.screening_key!(idempotency_key)
233
+ end
192
234
  path = RouteRequest.path!(route['path'], params)
193
235
  filters = RouteRequest.query!(query, route['query'] || [], name)
194
236
  payload = route['method'] == 'GET' ? nil : body!(name, route, body || {})
195
- @client.request(route['method'], path, body: payload, query: filters, signed: false)
237
+ @client.request(route['method'], path, body: payload, query: filters, signed: false, actor_id: actor, idempotency_key: key)
238
+ end
239
+
240
+ # The body of a keyed screening: the request hash and/or the keyword fields (a braceless call such as
241
+ # screen_name(name: 'X') arrives as keywords because these methods also take idempotency_key:).
242
+ def keyed_body(request, fields)
243
+ return request if fields.empty?
244
+ return fields if request.nil?
245
+ raise ConfigurationError, 'request must be a Hash.' unless request.is_a?(Hash)
246
+
247
+ request.merge(fields)
248
+ end
249
+
250
+ def actor!(actor_id)
251
+ actor = actor_id.is_a?(String) ? actor_id.strip : ''
252
+ return actor if actor.match?(ACTOR_ID)
253
+
254
+ raise ConfigurationError, 'actor_id (X-Actor-Id) is required: the person in your organization acting, 1-64 characters of ' \
255
+ 'letters, digits and . _ @ + -'
196
256
  end
197
257
 
198
258
  def body!(name, route, body)
@@ -0,0 +1,215 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'securerandom'
5
+
6
+ module Lunixi
7
+ # Bulk screening (/api/v1/sanction/batches) of Lunixi::Sanction: screen a whole customer file or many
8
+ # API rows as one job and download signed reports. Writes need sanction:batch_screen and actor_id, sent
9
+ # as X-Actor-Id (the person in your organization acting; required with an API key); reads need
10
+ # sanction:batch_view. Requests are checked against SANCTION_ROUTES like the screening calls.
11
+ module SanctionBatch # rubocop:disable Metrics/ModuleLength -- one method per catalog operation
12
+ BATCH_KEY = /\A[\x21-\x7e]{8,160}\z/
13
+ BATCH_FILE_TYPES = {
14
+ '.csv' => 'text/csv',
15
+ '.xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
16
+ }.freeze
17
+
18
+ # The lists a bulk screening job can cover: { lists }.
19
+ def list_catalog(risk_domain: nil)
20
+ RouteResponse.unwrap(invoke('listCatalog', query: RouteRequest.compact('riskDomain' => risk_domain)))
21
+ end
22
+
23
+ # Opens a job (DRAFT): { name, retentionDays?, defaultSubjectType?, listScope?, headlineGroups? }.
24
+ # idempotency_key (8–160 printable characters) makes a retry return the same job; without one a random
25
+ # key is sent, so the SDK's own retries cannot open a second job. Returns { batch }.
26
+ def create_batch(request, actor_id:, idempotency_key: nil)
27
+ key = idempotency_key.nil? ? "sanction-batch-#{SecureRandom.uuid}" : idempotency_key
28
+ RouteResponse.unwrap(invoke('createBatch', body: request, actor_id: actor_id, idempotency_key: key))
29
+ end
30
+
31
+ # Adds API rows to a DRAFT job (chunk_no 0–99, at most 5000 rows): { accepted, rowCount }.
32
+ def append_batch_rows(batch_id, chunk_no:, rows:, actor_id:)
33
+ batch_write('appendBatchRows', batch_id, { 'chunkNo' => chunk_no, 'rows' => rows }, actor_id)
34
+ end
35
+
36
+ # File upload, step 1: { uploadId, partSize, expiresAt, parts }. upload_batch_file runs the whole upload.
37
+ def create_batch_upload_session(batch_id, file_name:, content_type:, bytes:, sha256:, actor_id:)
38
+ body = { 'fileName' => file_name, 'contentType' => content_type, 'bytes' => bytes, 'sha256' => sha256 }
39
+ batch_write('createBatchUploadSession', batch_id, body, actor_id)
40
+ end
41
+
42
+ # File upload, last step (parts: [{ partNo, etag }]): { batch, columns, suggestedMapping, ... }.
43
+ def complete_batch_upload(batch_id, upload_id:, parts:, actor_id:)
44
+ batch_write('completeBatchUpload', batch_id, { 'uploadId' => upload_id, 'parts' => parts }, actor_id)
45
+ end
46
+
47
+ # Uploads a .csv or .xlsx file in one call: its sha256, the upload session, a PUT of every part to its
48
+ # signed URL and the completion. The PUTs go straight to the storage host with only the body and its
49
+ # Content-Length, never the access token. A failed PUT is not retried and the upload is not completed;
50
+ # call upload_batch_file again (a new session replaces the open one).
51
+ def upload_batch_file(batch_id, path, actor_id:, file_name: nil, content_type: nil)
52
+ actor = actor!(actor_id)
53
+ name = (file_name || File.basename(path.to_s)).strip
54
+ type = BATCH_FILE_TYPES[File.extname(name).downcase]
55
+ raise ConfigurationError, "file_name must end in .csv or .xlsx; got #{name.inspect}." if type.nil?
56
+ raise ConfigurationError, 'The batch file cannot be read.' unless File.file?(path) && File.readable?(path)
57
+
58
+ size = File.size(path)
59
+ raise ConfigurationError, 'The batch file is empty.' if size.zero?
60
+
61
+ session = create_batch_upload_session(batch_id, file_name: name, content_type: content_type || type, bytes: size,
62
+ sha256: Digest::SHA256.file(path).hexdigest, actor_id: actor)
63
+ parts = upload_parts!(session, size)
64
+ uploaded = File.open(path, 'rb') do |file|
65
+ parts.map do |part|
66
+ data = file.read(part['bytes'])
67
+ raise ConfigurationError, 'The batch file became shorter while it was being uploaded.' unless data&.bytesize == part['bytes']
68
+
69
+ { 'partNo' => part['partNo'], 'etag' => put_part(part, data) }
70
+ end
71
+ end
72
+ complete_batch_upload(batch_id, upload_id: session['uploadId'], parts: uploaded, actor_id: actor)
73
+ end
74
+
75
+ # Confirms which file column is which field: { batch } (VALIDATING).
76
+ def set_batch_column_mapping(batch_id, mapping:, actor_id:, default_subject_type: nil)
77
+ raise ConfigurationError, 'mapping must be a Hash of column header to field.' unless mapping.is_a?(Hash)
78
+
79
+ body = RouteRequest.compact('mapping' => mapping, 'defaultSubjectType' => default_subject_type)
80
+ batch_write('setBatchColumnMapping', batch_id, body, actor_id)
81
+ end
82
+
83
+ # Validation summary: { status, counts, invalidByReason, samples }.
84
+ def get_batch_validation(batch_id)
85
+ batch_read('getBatchValidation', batch_id)
86
+ end
87
+
88
+ # What the job will cost: { estimateRows, estimateAmountMinor, unitFeeMinor, currency, pricingSource }.
89
+ def get_batch_estimate(batch_id)
90
+ batch_read('getBatchEstimate', batch_id)
91
+ end
92
+
93
+ # Queues the job, confirming the shown estimate (409 sanction.batch.estimate_mismatch when it changed).
94
+ def submit_batch(batch_id, estimate_amount_minor:, actor_id:)
95
+ unless estimate_amount_minor.is_a?(String) && estimate_amount_minor.match?(/\A(0|[1-9][0-9]*)\z/)
96
+ raise ConfigurationError, "estimate_amount_minor must be the estimate's integer string in minor units."
97
+ end
98
+
99
+ batch_write('submitBatch', batch_id, { 'confirmEstimate' => true, 'estimateAmountMinor' => estimate_amount_minor }, actor_id)
100
+ end
101
+
102
+ # Cancels the job; rows screened before stay billed: { batch, note }.
103
+ def cancel_batch(batch_id, actor_id:, reason: nil)
104
+ batch_write('cancelBatch', batch_id, RouteRequest.compact('reason' => reason), actor_id)
105
+ end
106
+
107
+ # Your jobs, newest first. Filters: limit, cursor, status (one or a list).
108
+ def list_batches(**filters)
109
+ page('listBatches', csv(filters, 'status'))
110
+ end
111
+
112
+ def iterate_batches(**filters, &block)
113
+ RouteResponse.each_item(filters, block) { |query| list_batches(**query) }
114
+ end
115
+
116
+ # One job: { batch }.
117
+ def get_batch(batch_id)
118
+ batch_read('getBatch', batch_id)
119
+ end
120
+
121
+ # Result rows without hits. Filters: limit, cursor, decision, tier, group, listId, basis,
122
+ # customerReference, status (decision and status: one or a list).
123
+ def list_batch_results(batch_id, **filters)
124
+ RouteResponse.page(invoke('listBatchResults', params: { 'batchId' => batch_id }, query: csv(filters, 'decision', 'status')))
125
+ end
126
+
127
+ def iterate_batch_results(batch_id, **filters, &block)
128
+ RouteResponse.each_item(filters, block) { |query| list_batch_results(batch_id, **query) }
129
+ end
130
+
131
+ # One result row with its hits: { row }. row_no starts at 1. A row may carry jurisdictionRisk: its countries on
132
+ # the country risk lists, each { field, country, listCode, listName, effect, listDate } (absent on older rows;
133
+ # field may be empty).
134
+ def get_batch_result_row(batch_id, row_no)
135
+ raise ConfigurationError, 'row_no must be a positive integer.' unless row_no.is_a?(Integer) && row_no.positive?
136
+
137
+ RouteResponse.unwrap(invoke('getBatchResultRow', params: { 'batchId' => batch_id, 'rowNo' => row_no.to_s }))
138
+ end
139
+
140
+ # A signed report URL (300 s): { url, expiresAt, sha256, bytes, fileName }. lang (tr, en) picks the pdf language.
141
+ def get_batch_report_url(batch_id, format, lang: nil)
142
+ raise ConfigurationError, "format must be one of #{SanctionBatchReportFormat::ALL.join(', ')}." unless SanctionBatchReportFormat::ALL.include?(format)
143
+ raise ConfigurationError, 'lang must be tr or en.' unless lang.nil? || %w[tr en].include?(lang)
144
+
145
+ params = { 'batchId' => batch_id, 'format' => format }
146
+ RouteResponse.unwrap(invoke('getBatchReportUrl', params: params, query: RouteRequest.compact('lang' => lang)))
147
+ end
148
+
149
+ # Erases the job's rows, results and reports now: { certificate }.
150
+ def erase_batch(batch_id, actor_id:, reason: nil)
151
+ batch_write('eraseBatch', batch_id, RouteRequest.compact('reason' => reason), actor_id)
152
+ end
153
+
154
+ # The erasure certificate of an erased job: { certificate }.
155
+ def get_batch_erasure_certificate(batch_id)
156
+ batch_read('getBatchErasureCertificate', batch_id)
157
+ end
158
+
159
+ private
160
+
161
+ def batch_write(name, batch_id, body, actor_id)
162
+ RouteResponse.unwrap(invoke(name, params: { 'batchId' => batch_id }, body: body, actor_id: actor_id))
163
+ end
164
+
165
+ def batch_read(name, batch_id)
166
+ RouteResponse.unwrap(invoke(name, params: { 'batchId' => batch_id }))
167
+ end
168
+
169
+ def batch_key!(key)
170
+ return key if key.is_a?(String) && key.match?(BATCH_KEY)
171
+
172
+ raise ConfigurationError, 'idempotency_key must be 8-160 printable ASCII characters without spaces.'
173
+ end
174
+
175
+ # One value or a list, sent comma-separated (the gateway splits it).
176
+ def csv(filters, *keys)
177
+ keys.each_with_object(filters.dup) do |key, out|
178
+ found = out.keys.find { |name| name.to_s == key }
179
+ next if found.nil? || !out[found].is_a?(Array)
180
+
181
+ joined = out[found].map { |value| value.to_s.strip }.reject(&:empty?).join(',')
182
+ out[found] = joined.empty? ? '' : joined
183
+ end
184
+ end
185
+
186
+ # The session's parts, used only if they are 1..n with http(s) URLs adding up to the file.
187
+ def upload_parts!(session, size) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity -- multipart upload state machine
188
+ parts = session.is_a?(Hash) ? session['parts'] : nil
189
+ usable = session.is_a?(Hash) && session['uploadId'].is_a?(String) && !session['uploadId'].empty? && parts.is_a?(Array) && !parts.empty?
190
+ usable &&= parts.each_with_index.all? do |part, index|
191
+ part.is_a?(Hash) && part['partNo'] == index + 1 && part['url'].is_a?(String) && part['url'].match?(%r{\Ahttps?://}i) &&
192
+ part['bytes'].is_a?(Integer) && part['bytes'].positive?
193
+ end
194
+ return parts if usable && parts.sum { |part| part['bytes'] } == size
195
+
196
+ raise ApiError.new(status: 0, message: 'The batch upload session did not return usable upload parts.')
197
+ end
198
+
199
+ # The PUT of one part to its signed URL. It deliberately does not use Client#request: the access token
200
+ # must never reach the storage host. Only the body and its Content-Length are sent; returns the ETag.
201
+ def put_part(part, data)
202
+ raise ConfigurationError, 'The batch file upload needs a storage transport.' if @storage_transport.nil?
203
+
204
+ response = @storage_transport.call(method: 'PUT', uri: URI.parse(part['url']), headers: { 'Content-Length' => data.bytesize.to_s }.freeze, body: data)
205
+ raise TransportError, 'Batch file upload to storage returned an invalid response' unless response.is_a?(Response) && response.status.is_a?(Integer)
206
+ raise ApiError.new(status: response.status, code: PaymentLinkImageRules.storage_error_code(response.body)) unless response.status.between?(200, 299)
207
+
208
+ etag = response.headers.is_a?(Hash) ? response.headers.find { |name, _| name.to_s.casecmp?('etag') }&.last : nil
209
+ etag = etag.first if etag.is_a?(Array)
210
+ raise ApiError.new(status: response.status, code: 'STORAGE_ETAG_MISSING') if etag.nil? || etag.to_s.empty?
211
+
212
+ etag.to_s
213
+ end
214
+ end
215
+ end