lunixi-sdk 2.0.2 → 2.2.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.
@@ -41,6 +41,26 @@ module Lunixi
41
41
  ALL = [OTP, REDIRECT, DISPLAY, APP_APPROVAL, INPUT].freeze
42
42
  end
43
43
 
44
+ # The envelope code of payments.void on a PROCESSING payment with an open request waiting for the buyer
45
+ # (Request to Pay approval, bank transfer instruction, QR): the request is cancelled through the shared
46
+ # cancellation. Follow the final result with payments.get or the webhook.
47
+ module PaymentPendingActionCode
48
+ # The request was closed, no money moved; the payment is FAILED.
49
+ CANCELLED = 'payment.pending_action.cancelled'
50
+ # The buyer paid during the cancellation; the payment is CAPTURED.
51
+ ALREADY_COMPLETED = 'payment.pending_action.already_completed'
52
+ # The provider does not withdraw the request now; it stays open (the buyer can reject it).
53
+ NOT_CANCELLABLE = 'payment.pending_action.not_cancellable'
54
+ # The result is being verified; the payment is NEEDS_RECONCILIATION.
55
+ CANCEL_UNCONFIRMED = 'payment.pending_action.cancel_unconfirmed'
56
+ # Nothing open to cancel.
57
+ NOT_OPEN = 'payment.pending_action.not_open'
58
+ # The request is being processed; try again in a few seconds.
59
+ BUSY = 'payment.pending_action.busy'
60
+
61
+ ALL = [CANCELLED, ALREADY_COMPLETED, NOT_CANCELLABLE, CANCEL_UNCONFIRMED, NOT_OPEN, BUSY].freeze
62
+ end
63
+
44
64
  # providerSelection of a method in payments.list_payment_methods.
45
65
  module ProviderSelection
46
66
  # Card: routing picks the provider; providerCode is not sent.
@@ -71,11 +91,11 @@ module Lunixi
71
91
  # Body fields of POST /payments/direct/payment.
72
92
  DIRECT_METHOD_PAYMENT_FIELDS = (%w[
73
93
  paymentMethod amount currency orderId paymentChannel paymentGroup callbackUrl locale description customerId
74
- preauth buyer shippingAddress billingAddress basketItems card installment installmentQuoteToken force3D metadata
94
+ preauth buyer shippingAddress billingAddress basketItems card installment installmentQuoteToken force3D cardRewardSelection routing metadata
75
95
  ] + METHOD_BLOCK_FIELDS).freeze
76
96
 
77
97
  # Fields that belong to a card payment only (paymentMethod CARD).
78
- CARD_ONLY_FIELDS = %w[card installment installmentQuoteToken force3D].freeze
98
+ CARD_ONLY_FIELDS = %w[card installment installmentQuoteToken force3D cardRewardSelection].freeze
79
99
 
80
100
  # Body fields of POST /payments/{paymentId}/actions/{actionId}/confirm a merchant server sends.
81
101
  # The hosted form's checkout token fields are never sent by this SDK.
@@ -9,10 +9,12 @@ module Lunixi
9
9
  PDF_ACCEPT = 'application/pdf, application/json'
10
10
  OMITTED_AMOUNT = Object.new.freeze
11
11
  private_constant :OMITTED_AMOUNT
12
- attr_reader :client
12
+ attr_reader :client, :connections
13
13
 
14
14
  def initialize(client)
15
15
  @client = client
16
+ # Your provider connections, the targets of routing.credentialId (connections.list).
17
+ @connections = PaymentConnections.new(client)
16
18
  end
17
19
 
18
20
  # Create hosted/embedded checkout using integer minor units and a durable attempt key.
@@ -29,6 +31,9 @@ module Lunixi
29
31
  # prices add up to +amount+); +shippingAddress+ when an item is PHYSICAL. A missing field raises
30
32
  # ConfigurationError naming its path before sending.
31
33
  #
34
+ # Optional +routing+ ({ providerCode:, credentialId:, mode: }, RoutingPinMode) pins the payment to a
35
+ # provider and/or one of your connections; it is written to the intent and the browser never sees it.
36
+ #
32
37
  # @param body [Hash] gateway body: +amount+ (canonical minor-unit string), +currency+, +orderId+,
33
38
  # the order details and optional fields such as +callbackUrl+ and +enabledInstallments+
34
39
  # @param idempotency_key [String] the persisted key of this checkout attempt
@@ -124,9 +129,24 @@ module Lunixi
124
129
 
125
130
  # Start a payment with any method from the merchant server (POST /payments/direct/payment). Build
126
131
  # the body with DirectMethodPaymentRequest or pass a raw Hash; both are checked before sending,
127
- # the order details (OrderDetails) included.
132
+ # the order details (OrderDetails) included. routing (DirectMethodPaymentRequest#with_routing) pins
133
+ # the payment to a provider or one of your connections: STRICT answers 422
134
+ # payment.routing.pin_not_eligible when the target cannot take it, PREFER falls back to normal
135
+ # routing; a pinned payment's response carries data.routing (RoutingPin.result).
128
136
  # When the buyer must act, data.action says how (PaymentActionType); a BANK_TRANSFER payment
129
137
  # answers with a DISPLAY action read by BankTransferInstruction.from_response.
138
+ # List reward programmes without creating a payment.
139
+ def list_card_rewards(body)
140
+ Money.minor(body.fetch('amount'))
141
+ client.request('POST', "#{BASE}/direct/rewards/options", body: body)
142
+ end
143
+
144
+ # Query an expiring selection bound to this card and order.
145
+ def query_card_rewards(body)
146
+ Money.minor(body.fetch('amount'))
147
+ client.request('POST', "#{BASE}/direct/rewards/query", body: body)
148
+ end
149
+
130
150
  def direct_method_payment(body_or_request, idempotency_key: nil)
131
151
  body = body_or_request.is_a?(DirectMethodPaymentRequest) ? body_or_request.to_h : DirectMethodPaymentRequest.payload!(body_or_request)
132
152
  OrderDetails.check!(body, 'A direct method payment')
@@ -194,12 +214,15 @@ module Lunixi
194
214
  client.request('POST', "#{BASE}/#{payment_id}/refund", body: body, idempotency_key: Client.idempotency_key!(idempotency_key))
195
215
  end
196
216
 
197
- # Void an authorization without inventing a settlement success result.
217
+ # Void an authorization without inventing a settlement success result. On a PROCESSING payment with an
218
+ # open request waiting for the buyer (Request to Pay, bank transfer instruction, QR) the same call
219
+ # cancels the request; the answer's code is a PaymentPendingActionCode value.
198
220
  def void(payment_id, idempotency_key:)
199
221
  client.request('POST', "#{BASE}/#{identifier!(payment_id)}/void", idempotency_key: Client.idempotency_key!(idempotency_key))
200
222
  end
201
223
 
202
- # Start a 1–5 leg split payment; running statuses are returned, never marked paid. The body
224
+ # Start a 1–5 leg split payment; running statuses are returned, never marked paid. legs[].routing
225
+ # pins one leg (a non-card leg's providerCode must equal it). The body
203
226
  # (SPLIT_PAYMENT_FIELDS) carries the order details: buyer, billingAddress, basketItems and
204
227
  # shippingAddress for a PHYSICAL item; a missing field raises ConfigurationError before sending.
205
228
  def split(body, idempotency_key:)
@@ -297,7 +320,7 @@ module Lunixi
297
320
 
298
321
  validate_basket!(data['basketItems'], data['amount']) if data.key?('basketItems')
299
322
  data['enabledInstallments'] = EnabledInstallments.check!(data['enabledInstallments']) if data.key?('enabledInstallments')
300
- data
323
+ RoutingPin.field!(data)
301
324
  end
302
325
 
303
326
  def sellers!(sellers, amount)
@@ -12,7 +12,7 @@ module Lunixi
12
12
  end
13
13
 
14
14
  # Reads product webhooks through the signature check, never around it. Not a public API; use
15
- # BankConnectWebhook, BankTransferWebhook or InsuranceWebhook.
15
+ # BankConnectWebhook, BankTransferWebhook, BankPosWebhook or InsuranceWebhook.
16
16
  module ProductWebhook
17
17
  module_function
18
18
 
@@ -82,6 +82,22 @@ module Lunixi
82
82
  end
83
83
  end
84
84
 
85
+ # bank_pos.day_closed (BankPosEvents): a POS account's day closed; data holds BANK_POS_DAY_CLOSED_FIELDS
86
+ # (acquiringAccountId is the POS account id; amounts are minor-unit strings, counts integers).
87
+ module BankPosWebhook
88
+ FIELDS = BankPosEvents::ALL.to_h { |type| [type, BANK_POS_DAY_CLOSED_FIELDS] }.freeze
89
+
90
+ module_function
91
+
92
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
93
+ ProductWebhook.parse(raw_body, headers, secret_or_verifier, FIELDS, 'bank POS', tolerance)
94
+ end
95
+
96
+ def from_event(verified_event)
97
+ ProductWebhook.read(verified_event, FIELDS, 'bank POS')
98
+ end
99
+ end
100
+
85
101
  # insurance.* (InsuranceEvents). An order event's data holds INSURANCE_WEBHOOK_FIELDS; the lead event
86
102
  # (insurance.lead.submitted) holds INSURANCE_LEAD_WEBHOOK_FIELDS and is not an order. Decide on the
87
103
  # order from the webhook; get_order shows its state.
@@ -47,13 +47,14 @@ module Lunixi
47
47
  end
48
48
 
49
49
  # The raw answer of one route. params: path segments by wire name; query: filters; body: the request
50
- # Hash (wire names, snake_case works too).
51
- def call(name, params: {}, query: nil, body: nil, idempotency_key: nil)
50
+ # Hash (wire names, snake_case works too). A nil body field is left out, except the wire names in
51
+ # null_fields: those are sent as an explicit JSON null (a required one is then present).
52
+ def call(name, params: {}, query: nil, body: nil, idempotency_key: nil, null_fields: [])
52
53
  route = @routes.fetch(name) { raise ArgumentError, "Unknown route #{name}." }
53
54
  path = RouteRequest.path!(route['path'], params)
54
55
  key = key!(name, route['idempotencyKey'] || 'none', idempotency_key)
55
56
  filters = query.nil? ? {} : filters!(name, route, query)
56
- payload = body!(name, route, body)
57
+ payload = body!(name, route, body, null_fields)
57
58
  money = path.match?(MONEY_ROUTE)
58
59
  if money
59
60
  WireMoney.validate_wire(payload)
@@ -112,9 +113,13 @@ module Lunixi
112
113
  end
113
114
  end
114
115
 
115
- def body!(name, route, body)
116
+ def body!(name, route, body, null_fields = []) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity -- mirrors the catalog body rules
116
117
  if route.key?('required') || route.key?('optional')
117
- plain = RouteRequest.fields!(body || {}, route['required'] || [], route['optional'] || [], name)
118
+ explicit_null = null_fields.select { |field| body.is_a?(Hash) && body.key?(field) && body[field].nil? }
119
+ # An explicit null is validated by the caller and re-added below; keep it out of the field check.
120
+ checked = explicit_null.empty? ? (body || {}) : body.except(*explicit_null)
121
+ plain = RouteRequest.fields!(checked, (route['required'] || []) - explicit_null, route['optional'] || [], name)
122
+ explicit_null.each { |field| plain[field] = nil }
118
123
  elsif route['free']
119
124
  plain = RouteRequest.wire_hash!(body.nil? && route['optionalBody'] ? {} : body, "#{name} body")
120
125
  else
@@ -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)