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.
@@ -59,14 +59,16 @@ module Lunixi
59
59
  end
60
60
 
61
61
  # What a bank or a connection offers. OUTGOING_TRANSFER and FX_EXCHANGE open bank_connect.transfers and
62
- # bank_connect.fx.
62
+ # bank_connect.fx. POS_ACQUIRING: the bank's merchant (POS) records are read (bank_connect.pos_accounts);
63
+ # it cannot be turned off.
63
64
  module BankCapability
64
65
  ACCOUNT_LIST = 'ACCOUNT_LIST'
65
66
  BALANCE = 'BALANCE'
66
67
  TRANSACTIONS = 'TRANSACTIONS'
67
68
  OUTGOING_TRANSFER = 'OUTGOING_TRANSFER'
68
69
  FX_EXCHANGE = 'FX_EXCHANGE'
69
- ALL = [ACCOUNT_LIST, BALANCE, TRANSACTIONS, OUTGOING_TRANSFER, FX_EXCHANGE].freeze
70
+ POS_ACQUIRING = 'POS_ACQUIRING'
71
+ ALL = [ACCOUNT_LIST, BALANCE, TRANSACTIONS, OUTGOING_TRANSFER, FX_EXCHANGE, POS_ACQUIRING].freeze
70
72
  end
71
73
 
72
74
  # QUEUED: the read starts now or is already waiting. SCHEDULED: it runs at scheduledAt.
@@ -110,6 +112,38 @@ module Lunixi
110
112
  ALL = [INTERNAL, INTRABANK, FAST, EFT, UNKNOWN].freeze
111
113
  end
112
114
 
115
+ # When a previewed transfer arrives: INSTANT (internal, same bank, FAST) or BANK_HOURS (EFT).
116
+ module BankTransferArrival
117
+ INSTANT = 'INSTANT'
118
+ BANK_HOURS = 'BANK_HOURS'
119
+ UNKNOWN = 'UNKNOWN'
120
+ ALL = [INSTANT, BANK_HOURS, UNKNOWN].freeze
121
+ end
122
+
123
+ # The receiving bank's FAST status in a route preview; UNKNOWN means EFT is used (safe default).
124
+ module BankFastStatus
125
+ ACTIVE = 'ACTIVE'
126
+ NOT_PARTICIPANT = 'NOT_PARTICIPANT'
127
+ OUT_OF_SERVICE = 'OUT_OF_SERVICE'
128
+ UNKNOWN = 'UNKNOWN'
129
+ ALL = [ACTIVE, NOT_PARTICIPANT, OUT_OF_SERVICE, UNKNOWN].freeze
130
+ end
131
+
132
+ # Machine codes in transfers.preview's notes; they explain why a route was chosen.
133
+ module BankTransferPreviewNote
134
+ OWN_ACCOUNT_INTERNAL = 'own_account_internal'
135
+ OWN_ACCOUNT_OTHER_CONNECTION = 'own_account_other_connection'
136
+ OWN_ACCOUNT_CURRENCY_MISMATCH = 'own_account_currency_mismatch'
137
+ FAST_LIMIT_EXCEEDED = 'fast_limit_exceeded'
138
+ FAST_RECEIVER_NOT_PARTICIPANT = 'fast_receiver_not_participant'
139
+ FAST_RECEIVER_OUT_OF_SERVICE = 'fast_receiver_out_of_service'
140
+ FAST_PARTICIPANTS_UNKNOWN = 'fast_participants_unknown'
141
+ FAST_SENDER_IDENTITY_MISSING = 'fast_sender_identity_missing'
142
+ EFT_LARGE_AMOUNT_DESCRIPTION_REQUIRED = 'eft_large_amount_description_required'
143
+ ALL = [OWN_ACCOUNT_INTERNAL, OWN_ACCOUNT_OTHER_CONNECTION, OWN_ACCOUNT_CURRENCY_MISMATCH, FAST_LIMIT_EXCEEDED, FAST_RECEIVER_NOT_PARTICIPANT,
144
+ FAST_RECEIVER_OUT_OF_SERVICE, FAST_PARTICIPANTS_UNKNOWN, FAST_SENDER_IDENTITY_MISSING, EFT_LARGE_AMOUNT_DESCRIPTION_REQUIRED].freeze
145
+ end
146
+
113
147
  module BankTransferInitiatedVia
114
148
  PANEL = 'PANEL'
115
149
  API = 'API'
@@ -143,6 +177,60 @@ module Lunixi
143
177
  ALL = [CREATED, COMPLETED, FAILED, RETURNED].freeze
144
178
  end
145
179
 
180
+ # Type of a POS transaction in the bank's records; the amount is positive, the direction comes from the
181
+ # type.
182
+ module BankPosTransactionType
183
+ SALE = 'SALE'
184
+ INSTALLMENT_SALE = 'INSTALLMENT_SALE'
185
+ REFUND = 'REFUND'
186
+ VOID = 'VOID'
187
+ PREAUTH_CLOSE = 'PREAUTH_CLOSE'
188
+ BONUS_SALE = 'BONUS_SALE'
189
+ OTHER = 'OTHER'
190
+ ALL = [SALE, INSTALLMENT_SALE, REFUND, VOID, PREAUTH_CLOSE, BONUS_SALE, OTHER].freeze
191
+ end
192
+
193
+ # CARD_PRESENT, ECOMMERCE, MOTO (mail/telephone order) or UNKNOWN.
194
+ module BankPosChannel
195
+ CARD_PRESENT = 'CARD_PRESENT'
196
+ ECOMMERCE = 'ECOMMERCE'
197
+ MOTO = 'MOTO'
198
+ UNKNOWN = 'UNKNOWN'
199
+ ALL = [CARD_PRESENT, ECOMMERCE, MOTO, UNKNOWN].freeze
200
+ end
201
+
202
+ # DAILY: intraday (provisional). END_OF_DAY: the bank's final record. FORWARD: forward value date list.
203
+ module BankPosTransactionSource
204
+ DAILY = 'DAILY'
205
+ END_OF_DAY = 'END_OF_DAY'
206
+ FORWARD = 'FORWARD'
207
+ ALL = [DAILY, END_OF_DAY, FORWARD].freeze
208
+ end
209
+
210
+ # POS account and terminal status. MISSING: not in the bank's latest list; the record is kept.
211
+ module BankPosRecordStatus
212
+ ACTIVE = 'ACTIVE'
213
+ MISSING = 'MISSING'
214
+ ALL = [ACTIVE, MISSING].freeze
215
+ end
216
+
217
+ # End-of-day read status of one POS account day.
218
+ module BankPosDayStatus
219
+ PENDING = 'PENDING'
220
+ COMPLETE = 'COMPLETE'
221
+ FAILED = 'FAILED'
222
+ ALL = [PENDING, COMPLETE, FAILED].freeze
223
+ end
224
+
225
+ # POS account webhook events (subscription bank_pos.*). DAY_CLOSED: a POS account's day closed, the
226
+ # bank's end of day was read for the first time (once per account and day, usually after 01:30 the next
227
+ # day). Read it with Lunixi::BankPosWebhook.parse; data holds BANK_POS_DAY_CLOSED_FIELDS.
228
+ module BankPosEvents
229
+ DAY_CLOSED = 'bank_pos.day_closed'
230
+ PATTERN = 'bank_pos.*'
231
+ ALL = [DAY_CLOSED].freeze
232
+ end
233
+
146
234
  # Query filters each read route accepts (the gateway rejects any other with 400).
147
235
  BANK_CONNECT_FILTERS = {
148
236
  'listBanks' => %w[limit cursor].freeze,
@@ -159,15 +247,31 @@ module Lunixi
159
247
  BANK_CONNECT_BOOKED_RANGE_MAX_DAYS = 92
160
248
  BANK_CONNECT_CURSOR_MAX_LENGTH = 2048
161
249
 
250
+ # Query fields each POS account list accepts (the gateway rejects any other with 400).
251
+ BANK_POS_FILTERS = {
252
+ 'listPosAccounts' => %w[limit cursor connectionId].freeze,
253
+ 'listPosTerminals' => %w[limit cursor].freeze,
254
+ 'listPosTransactions' => %w[limit cursor terminalId from to type cardBrand minAmountMinor maxAmountMinor provisional].freeze,
255
+ 'listPosStatement' => %w[limit cursor terminalId from to].freeze
256
+ }.freeze
257
+ # Widest from … to window of one POS transaction request, in days.
258
+ BANK_POS_TRANSACTION_RANGE_MAX_DAYS = 92
259
+ # Card brands the POS transaction filter takes (the gateway accepts 1–16 letters).
260
+ BANK_POS_CARD_BRAND_PATTERN = /\A[A-Za-z]{1,16}\z/
261
+
162
262
  # Transfer and exchange routes: method, path, body fields, query fields and the Idempotency-Key rule.
163
263
  # The same table as the Node SDK's BANK_TRANSFER_ROUTES (forbidNonWhitelisted: any other field is a
164
264
  # 400); the parity test compares it with the shared catalog. Every route is signed and needs
165
265
  # bank-connect:transfer plus a key with an IP allowlist.
166
266
  BANK_TRANSFER_ROUTES = {
167
267
  'listTransferPurposes' => RouteRequest.route('GET', '/api/v1/bank-connect/transfer-purposes', idempotency_key: false, query: %w[connectionId]),
268
+ 'previewTransfer' => RouteRequest.route('POST', '/api/v1/bank-connect/transfers/preview',
269
+ idempotency_key: false, required: %w[accountId amountMinor],
270
+ optional: %w[receiverIban recipientId receiverAccountId currency]),
168
271
  '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]),
272
+ idempotency_key: true, required: %w[accountId amountMinor],
273
+ optional: %w[receiverIban recipientId receiverAccountId receiverName currency paymentPurpose description
274
+ saveRecipient]),
171
275
  'listTransfers' => RouteRequest.route('GET', '/api/v1/bank-connect/transfers',
172
276
  idempotency_key: false, query: %w[limit cursor accountId status createdFrom createdTo]),
173
277
  'getTransfer' => RouteRequest.route('GET', '/api/v1/bank-connect/transfers/:transferId', idempotency_key: false),
@@ -177,9 +281,22 @@ module Lunixi
177
281
  optional: %w[sourceAmountMinor targetAmountMinor]),
178
282
  'createFxOrder' => RouteRequest.route('POST', '/api/v1/bank-connect/fx/orders', idempotency_key: true, required: %w[quoteId], optional: %w[description]),
179
283
  '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)
284
+ 'getFxOrder' => RouteRequest.route('GET', '/api/v1/bank-connect/fx/orders/:orderId', idempotency_key: false),
285
+ 'listTransferRecipients' => RouteRequest.route('GET', '/api/v1/bank-connect/transfer-recipients', idempotency_key: false, query: %w[limit cursor q]),
286
+ 'createTransferRecipient' => RouteRequest.route('POST', '/api/v1/bank-connect/transfer-recipients',
287
+ idempotency_key: false, required: %w[iban name], optional: %w[nickname]),
288
+ 'updateTransferRecipient' => RouteRequest.route('PATCH', '/api/v1/bank-connect/transfer-recipients/:recipientId',
289
+ idempotency_key: false, required: [], optional: %w[name nickname]),
290
+ 'deleteTransferRecipient' => RouteRequest.route('DELETE', '/api/v1/bank-connect/transfer-recipients/:recipientId', idempotency_key: false)
181
291
  }.freeze
182
292
 
293
+ # The receiver of a transfer or a preview: exactly one of these fields.
294
+ BANK_TRANSFER_RECEIVER_FIELDS = %w[receiverIban recipientId receiverAccountId].freeze
295
+ # Longest saved recipient nickname.
296
+ BANK_TRANSFER_RECIPIENT_NICKNAME_MAX = 64
297
+ # Longest q of transfer_recipients.list.
298
+ BANK_TRANSFER_RECIPIENT_SEARCH_MAX = 64
299
+
183
300
  # Idempotency-Key of create_transfer / create_order: 8–200 printable ASCII characters.
184
301
  BANK_TRANSFER_IDEMPOTENCY_KEY_PATTERN = RouteRequest::PRINTABLE_IDEMPOTENCY_KEY
185
302
  # paymentPurpose: a code from transfers.list_purposes.
@@ -202,4 +319,9 @@ module Lunixi
202
319
  transferId connectionId accountId bankEftCode bankName status rail amountMinor currency receiverIbanMasked receiverNameMasked
203
320
  paymentPurpose description failureCode idempotencyKey createdAt completedAt failedAt returnedAt
204
321
  ].freeze
322
+ # data fields of the bank_pos.day_closed webhook (amounts are minor-unit strings, counts integers).
323
+ BANK_POS_DAY_CLOSED_FIELDS = %w[
324
+ acquiringAccountId connectionId bankEftCode bankName merchantNumber businessDate saleCount saleAmountMinor refundCount
325
+ refundAmountMinor netAmountMinor commissionAmountMinor currency
326
+ ].freeze
205
327
  end
@@ -49,7 +49,7 @@ module Lunixi
49
49
  bin_or_pan!(data['binOrPan']) unless data['binOrPan'].nil?
50
50
  installment!(data['installment']) unless data['installment'].nil?
51
51
  data['enabledInstallments'] = EnabledInstallments.check!(data['enabledInstallments']) if data.key?('enabledInstallments')
52
- data
52
+ RoutingPin.field!(data)
53
53
  end
54
54
 
55
55
  # Body of POST /api/v1/payments/cards: card, cardUserKey, an HTTPS callbackUrl, the buyer and the
@@ -116,6 +116,14 @@ module Lunixi
116
116
  self
117
117
  end
118
118
 
119
+ # The same routing you will charge with: the table is computed for the pinned target (STRICT: only
120
+ # the installments it is authorized for) and the quote token is bound to the pin; another pin
121
+ # answers 422 installment.quote.pin_mismatch.
122
+ def with_routing(value)
123
+ @payload['routing'] = RoutingPin.pin!(value)
124
+ self
125
+ end
126
+
119
127
  def to_h
120
128
  @payload.dup
121
129
  end
data/lib/lunixi/client.rb CHANGED
@@ -5,7 +5,7 @@ require 'time'
5
5
 
6
6
  module Lunixi
7
7
  # Thread-safe server-side gateway client. Responses retain the gateway envelope.
8
- class Client
8
+ class Client # rubocop:disable Metrics/ClassLength -- one entry point for every product client
9
9
  AUTH_PATH = '/api/v1/auth/token'
10
10
  METHODS = %w[GET HEAD POST PUT PATCH DELETE].freeze
11
11
  ACCEPT_JSON = 'application/json'
@@ -39,7 +39,8 @@ module Lunixi
39
39
  @physical_pos_management = PhysicalPosManagement.new(physical_pos_gateway)
40
40
  @wallet = Wallet.new(self)
41
41
  @bank_connect = BankConnect.new(self, max_retries: max_retries, backoff: ->(attempt) { pause(attempt, {}) })
42
- @sanction = Sanction.new(self)
42
+ # The transport also carries the bulk screening file part PUTs to storage, outside Client#request.
43
+ @sanction = Sanction.new(self, storage_transport: @transport)
43
44
  @insurance = Insurance.new(self)
44
45
  @subscriptions = Subscriptions.new(self)
45
46
  @kyc = Kyc.new(self)
@@ -51,8 +52,10 @@ module Lunixi
51
52
  # not invent field schemas, interpret financial results or retry an unsafe POST. With binary: true a
52
53
  # 2xx body is returned as frozen bytes; accept: names the media types the endpoint answers with.
53
54
  # max_retries: lowers the client's retry budget for this call (0 sends a single attempt).
54
- def request(method, path, body: nil, query: {}, idempotency_key: nil, signed: true, binary: false, accept: ACCEPT_JSON,
55
- max_retries: nil)
55
+ # actor_id is sent as X-Actor-Id: the person in your organization acting, on endpoints that record a
56
+ # person's action (validated by the operation that needs it).
57
+ def request(method, path, body: nil, query: {}, idempotency_key: nil, signed: true, binary: false, accept: ACCEPT_JSON, # rubocop:disable Metrics/ParameterLists -- transport options are keyword arguments
58
+ max_retries: nil, actor_id: nil)
56
59
  method = method.to_s.upcase
57
60
  raise ConfigurationError, 'Unsupported HTTP method' unless METHODS.include?(method)
58
61
  raise ConfigurationError, 'GET and HEAD cannot have a body' if %w[GET HEAD].include?(method) && !body.nil?
@@ -69,7 +72,9 @@ module Lunixi
69
72
  bytes = body.nil? ? nil : JsonBody.dump(body)
70
73
  raise ConfigurationError, 'Request body exceeds the size limit' if bytes && bytes.bytesize > 1024 * 1024
71
74
 
72
- perform_request(method, path, bytes, key, signed, binary, accept, retries)
75
+ raise ConfigurationError, 'Invalid X-Actor-Id' unless actor_id.nil? || actor_id.match?(/\A[A-Za-z0-9._@+-]{1,64}\z/)
76
+
77
+ perform_request(method, path, bytes, key, signed, binary, accept, retries, actor_id)
73
78
  end
74
79
 
75
80
  # Validates caller-owned durable keys; a generated key on every retry is unsafe.
@@ -95,6 +100,7 @@ module Lunixi
95
100
  return RouteRequest.printable_idempotency_key!(key) if path.match?(RouteRequest::PRINTABLE_KEY_ROUTE)
96
101
  return WalletInvoker.idempotency_key!(key) if path.match?(WalletInvoker::ROUTE)
97
102
  return RouteTable.idempotency_key!(key) if path.match?(RouteTable::KEY_ROUTE)
103
+ return Sanction.screening_key!(key) if path.match?(Sanction::SCREENING_ROUTE)
98
104
 
99
105
  self.class.idempotency_key!(key)
100
106
  end
@@ -106,13 +112,13 @@ module Lunixi
106
112
  max_retries
107
113
  end
108
114
 
109
- def perform_request(method, path, bytes, key, signed, binary, accept, max_retries)
115
+ def perform_request(method, path, bytes, key, signed, binary, accept, max_retries, actor_id = nil)
110
116
  safe_to_retry = %w[GET HEAD].include?(method) || !key.nil?
111
117
  retries = 0
112
118
  reauthenticated = false
113
119
  loop do
114
120
  token = access_token
115
- response = transmit(method, path, bytes, key, token, signed, accept)
121
+ response = transmit(method, path, bytes, key, token, signed, accept, actor_id)
116
122
  if response.status == 401 && !reauthenticated && safe_to_retry
117
123
  invalidate_token(token)
118
124
  reauthenticated = true
@@ -188,11 +194,12 @@ module Lunixi
188
194
  headers
189
195
  end
190
196
 
191
- def transmit(method, path, body, key, token, signed, accept = ACCEPT_JSON)
197
+ def transmit(method, path, body, key, token, signed, accept = ACCEPT_JSON, actor_id = nil)
192
198
  headers = { 'Accept' => accept, 'User-Agent' => "lunixi-sdk-ruby/#{VERSION}" }
193
199
  headers['Authorization'] = "Bearer #{token}" if token
194
200
  headers['Content-Type'] = 'application/json' unless body.nil?
195
201
  headers['Idempotency-Key'] = key if key
202
+ headers['X-Actor-Id'] = actor_id if actor_id
196
203
  headers.merge!(signed_headers(method, path, body)) if signed
197
204
  response = @transport.call(method: method, uri: URI.parse(@origin + path), headers: headers.freeze, body: body)
198
205
  unless response.is_a?(Response) && response.status.is_a?(Integer) && response.headers.is_a?(Hash) && response.body.is_a?(String)
@@ -71,6 +71,12 @@ module Lunixi
71
71
  end
72
72
 
73
73
  # Card only. true charges with 3D Secure: the response carries a REDIRECT action.
74
+ # Attach the buyer-approved amount from query_card_rewards.
75
+ def with_card_reward_selection(selection_id, amount_minor)
76
+ @payload['cardRewardSelection'] = { 'selectionId' => text(selection_id, 'selectionId'), 'amountMinor' => Money.minor(amount_minor) }
77
+ self
78
+ end
79
+
74
80
  def with_force3d(value)
75
81
  @payload['force3D'] = boolean(value, 'force3D')
76
82
  self
@@ -123,6 +129,15 @@ module Lunixi
123
129
  assign('metadata', value)
124
130
  end
125
131
 
132
+ # Pins the payment to a provider and/or one of your connections ({ providerCode:, credentialId:,
133
+ # mode: }, RoutingPinMode). Card: STRICT uses only the target (422 payment.routing.pin_not_eligible
134
+ # when it cannot take the payment, nothing is charged); PREFER (default) falls back to normal
135
+ # routing. Other methods: the block's providerCode stays strict and must equal routing.providerCode
136
+ # when both are given; mode applies to the connection choice. Not for BANK_TRANSFER.
137
+ def with_routing(value)
138
+ assign('routing', RoutingPin.pin!(value))
139
+ end
140
+
126
141
  def with_basket_items(items)
127
142
  raise ConfigurationError, 'basketItems must be an array of objects' unless items.is_a?(Array)
128
143
 
@@ -150,12 +165,18 @@ module Lunixi
150
165
  # string-keyed copy: known fields only, the chosen method's block and no other, card fields only
151
166
  # with CARD, block structure, promissory-note plan, shopping-loan basket, no providerCode for
152
167
  # BANK_TRANSFER. payments.direct_method_payment also checks the order details (OrderDetails).
153
- def self.payload!(body)
168
+ def self.payload!(body) # rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity -- one check per gateway rule, in gateway order
154
169
  raise ConfigurationError, 'A direct method payment needs a body; use DirectMethodPaymentRequest to build it' unless body.is_a?(Hash)
155
170
 
156
171
  data = JSON.parse(JsonBody.dump(body))
157
172
  raise ConfigurationError, 'Removed amount field; use amount in integer minor units' if %w[price paidPrice].any? { |key| data.key?(key) }
158
173
 
174
+ if data.key?('cardRewardSelection')
175
+ selection = data['cardRewardSelection']
176
+ raise ConfigurationError, 'Invalid reward selection' unless selection.is_a?(Hash) && selection['selectionId'].is_a?(String)
177
+
178
+ Money.minor(selection['amountMinor'])
179
+ end
159
180
  unknown = data.keys - DIRECT_METHOD_PAYMENT_FIELDS
160
181
  raise ConfigurationError, "Unknown direct method payment field(s): #{unknown.join(', ')}" unless unknown.empty?
161
182
 
@@ -172,7 +193,8 @@ module Lunixi
172
193
  %w[preauth force3D].each do |field|
173
194
  raise ConfigurationError, "#{field} must be a JSON boolean" if data.key?(field) && ![true, false].include?(data[field])
174
195
  end
175
- data
196
+ own = method == PaymentMethod::CARD ? nil : data[block_name]
197
+ RoutingPin.field!(data, payment_method: method, block_provider_code: own.is_a?(Hash) ? own['providerCode'] : nil)
176
198
  end
177
199
 
178
200
  # Block name of a method other than card; a method without a block cannot be paid here yet.
data/lib/lunixi/fraud.rb CHANGED
@@ -7,13 +7,14 @@ module Lunixi
7
7
  paymentId payment bankTransfer cryptoTransfer walletOperation billPayment loanApplication payout
8
8
  customer device session merchant mobileApp telemetry metadata identitySnapshot identityAssertion].freeze
9
9
 
10
- # Transaction event ingest (signed) and the persisted decision log.
11
- attr_reader :events, :decisions
10
+ # Transaction event ingest (signed), the persisted decision log and UK APP reimbursement claims.
11
+ attr_reader :events, :decisions, :uk_claims
12
12
 
13
13
  def initialize(client)
14
14
  @client = client
15
15
  @events = FraudEvents.new(client)
16
16
  @decisions = FraudDecisions.new(client)
17
+ @uk_claims = FraudUkClaims.new(client)
17
18
  end
18
19
 
19
20
  # Evaluate the documented fraud DTO; tenant identity comes from credentials.
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'time'
5
+
6
+ module Lunixi
7
+ # UK APP reimbursement claims (POST /api/v1/fraud/uk-claims). Opening a claim is the only claim action
8
+ # available with an API key; the assessment, approval, milestones and clock stops are done in the panel.
9
+ class FraudUkClaims
10
+ PATH = '/api/v1/fraud/uk-claims'
11
+ # X-Actor-Id: the analyst recording the claim.
12
+ ACTOR_ID = /\A[A-Za-z0-9._@+-]{1,64}\z/
13
+ POSITIVE_MINOR = /\A[1-9][0-9]*\z/
14
+ NONNEGATIVE_MINOR = /\A(0|[1-9][0-9]*)\z/
15
+ PAYMENTS_LIMIT = 200
16
+ LINKED_CLAIMS_LIMIT = 20
17
+
18
+ def initialize(client)
19
+ @client = client
20
+ end
21
+
22
+ # Records a UK APP reimbursement claim and returns the claim view (id, caseId, regime, claimState,
23
+ # amounts, deadlines, deadlineAlerts, channel: "api"). Keys are the wire names (UK_CLAIM_FIELDS,
24
+ # UK_CLAIM_PAYMENT_FIELDS); amounts are minor-unit strings and the currency is GBP only.
25
+ #
26
+ # actor_id is sent as X-Actor-Id: the analyst recording the claim. It is required with an API key and
27
+ # is stored as your declaration. Sending the same externalClaimRef again returns the existing claim.
28
+ def open(claim, actor_id:)
29
+ actor = actor!(actor_id)
30
+ body = claim!(claim)
31
+ RouteResponse.unwrap(@client.request('POST', PATH, body: body, signed: false, actor_id: actor))
32
+ end
33
+
34
+ private
35
+
36
+ def actor!(actor_id)
37
+ actor = actor_id.is_a?(String) ? actor_id.strip : ''
38
+ return actor if actor.match?(ACTOR_ID)
39
+
40
+ raise ConfigurationError, 'actor_id (X-Actor-Id) is required: the analyst recording the claim, 1-64 characters of ' \
41
+ 'letters, digits and . _ @ + -'
42
+ end
43
+
44
+ def claim!(claim)
45
+ raise ConfigurationError, 'UK claim must be an object' unless claim.is_a?(Hash)
46
+
47
+ data = JSON.parse(JsonBody.dump(claim))
48
+ unknown!(data, UK_CLAIM_FIELDS, 'UK claim')
49
+ raise ConfigurationError, 'role is required (sending | receiving).' if data['role'].nil?
50
+
51
+ one_of!(data, 'role', UK_CLAIM_ROLES)
52
+ iso!(data['reportedAt'], 'reportedAt')
53
+ one_of!(data, 'payerType', UK_CLAIM_PAYER_TYPES)
54
+ one_of!(data, 'reportedBy', UK_CLAIM_REPORTED_BY)
55
+ one_of!(data, 'scamType', UK_CLAIM_SCAM_TYPES)
56
+ raise ConfigurationError, 'UK reimbursement claims are GBP only.' if data.key?('currency') && data['currency'] != 'GBP'
57
+
58
+ payer!(data)
59
+ payments!(data['payments'])
60
+ data
61
+ end
62
+
63
+ def payer!(data)
64
+ staff = data['payerStaffCount']
65
+ raise ConfigurationError, 'payerStaffCount must be a non-negative integer.' if data.key?('payerStaffCount') && !(staff.is_a?(Integer) && staff >= 0)
66
+
67
+ %w[payerTurnoverOrBalanceEurMinor payerAnnualIncomeGbpMinor].each do |field|
68
+ minor!(data[field], NONNEGATIVE_MINOR, field) if data.key?(field)
69
+ end
70
+ linked = data['linkedClaimIds']
71
+ return unless data.key?('linkedClaimIds') && !(linked.is_a?(Array) && linked.size <= LINKED_CLAIMS_LIMIT)
72
+
73
+ raise ConfigurationError, "linkedClaimIds must be an array of at most #{LINKED_CLAIMS_LIMIT} ids."
74
+ end
75
+
76
+ def payments!(payments)
77
+ unless payments.is_a?(Array) && payments.size.between?(1, PAYMENTS_LIMIT)
78
+ raise ConfigurationError, "payments must be an array of 1 to #{PAYMENTS_LIMIT} payments."
79
+ end
80
+
81
+ payments.each_with_index do |payment, index|
82
+ where = "payments[#{index}]"
83
+ raise ConfigurationError, "#{where} must be an object." unless payment.is_a?(Hash)
84
+
85
+ unknown!(payment, UK_CLAIM_PAYMENT_FIELDS, where)
86
+ iso!(payment['executedAt'], "#{where}.executedAt")
87
+ raise ConfigurationError, "#{where}.amountMinor is required." unless payment.key?('amountMinor')
88
+
89
+ minor!(payment['amountMinor'], POSITIVE_MINOR, "#{where}.amountMinor")
90
+ one_of!(payment, 'scheme', UK_CLAIM_SCHEMES, where)
91
+ end
92
+ end
93
+
94
+ def unknown!(object, allowed, where)
95
+ key = object.keys.find { |name| !allowed.include?(name) }
96
+ raise ConfigurationError, "Unknown #{where} field \"#{key}\"; the gateway rejects it with 400." if key
97
+ end
98
+
99
+ def one_of!(object, field, values, where = nil)
100
+ return unless object.key?(field) && !values.include?(object[field])
101
+
102
+ raise ConfigurationError, "#{[where, field].compact.join('.')} must be one of: #{values.join(', ')}."
103
+ end
104
+
105
+ def iso!(value, field)
106
+ raise ConfigurationError, "#{field} must be an ISO 8601 date-time string." unless value.is_a?(String) && iso?(value.strip)
107
+ end
108
+
109
+ def iso?(value)
110
+ Time.iso8601(value)
111
+ true
112
+ rescue ArgumentError
113
+ begin
114
+ Date.iso8601(value)
115
+ true
116
+ rescue ArgumentError
117
+ false
118
+ end
119
+ end
120
+
121
+ def minor!(value, pattern, field)
122
+ return if value.is_a?(String) && value.match?(pattern)
123
+
124
+ raise ConfigurationError, "#{field} must be a minor-unit integer string (e.g. \"250000\"), not a number."
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Fraud webhook event types your endpoint can subscribe to, delivered in the platform's signed envelope
5
+ # and verified with WebhookVerifier. (Lunixi::FraudEvents is the transaction event client.)
6
+ module FraudWebhookEvents
7
+ # Async flow result is ready; correlate with decisionRequestId. Advisory: the synchronous decision stands.
8
+ FLOW_ASYNC_COMPLETED = 'fraud.flow.async_completed'
9
+ # A "Platform Event" node in your flow fired; label and data are the values you defined in the flow.
10
+ FLOW_ACTION_TRIGGERED = 'fraud.flow.action_triggered'
11
+ # Fraud API quota threshold reached, or a request was rejected with 429. Sent once per day and lane.
12
+ QUOTA_THRESHOLD_REACHED = 'fraud.quota.threshold_reached'
13
+ # One of your fraud alert rules fired.
14
+ ALERT_TRIGGERED = 'fraud.alert.triggered'
15
+ # An outage affecting fraud evaluation was detected or declared.
16
+ SERVICE_DEGRADED = 'fraud.service.degraded'
17
+ # The outage closed; carries the duration and how many decisions could not be checked.
18
+ SERVICE_RECOVERED = 'fraud.service.recovered'
19
+ # A scheduled report finished its period and was produced (no download link; download from the console).
20
+ REPORT_READY = 'fraud.report.ready'
21
+ # A UK APP claim obligation (receiving-firm notice, reimbursement, hard close) is due soon or overdue.
22
+ UK_CLAIM_DEADLINE = 'fraud.uk_claim.deadline'
23
+
24
+ ALL = [FLOW_ASYNC_COMPLETED, FLOW_ACTION_TRIGGERED, QUOTA_THRESHOLD_REACHED, ALERT_TRIGGERED, SERVICE_DEGRADED,
25
+ SERVICE_RECOVERED, REPORT_READY, UK_CLAIM_DEADLINE].freeze
26
+ end
27
+
28
+ # Every fraud webhook event type, in catalog order.
29
+ FRAUD_EVENT_TYPES = FraudWebhookEvents::ALL
30
+
31
+ # UK APP reimbursement claim: wire values of POST /api/v1/fraud/uk-claims. The gateway answers an unknown
32
+ # key with 400; these lists let the SDK fail locally with the offending key name.
33
+ UK_CLAIM_FIELDS = %w[role reportedAt externalClaimRef linkedClaimIds subMerchantRef victimRef payerType payerStaffCount
34
+ payerTurnoverOrBalanceEurMinor payerAnnualIncomeGbpMinor reportedBy scamType currency
35
+ counterpartyPspCode payments].freeze
36
+ UK_CLAIM_PAYMENT_FIELDS = %w[paymentRef fraudDecisionLogId traceId scheme executedAt amountMinor receivingPspCode payeeIban
37
+ payeeSortCode payeeAccountNumber warningRecord delayRecord].freeze
38
+ UK_CLAIM_ROLES = %w[sending receiving].freeze
39
+ UK_CLAIM_PAYER_TYPES = %w[individual micro_enterprise charity business_other].freeze
40
+ UK_CLAIM_REPORTED_BY = %w[victim agent].freeze
41
+ UK_CLAIM_SCAM_TYPES = %w[impersonation_bank_police impersonation_other investment romance purchase advance_fee invoice_mandate
42
+ ceo_fraud other].freeze
43
+ UK_CLAIM_SCHEMES = %w[faster_payments chaps bacs sepa swift on_us card other].freeze
44
+ # Deadline kinds carried by the fraud.uk_claim.deadline webhook event.
45
+ UK_CLAIM_DEADLINE_KINDS = %w[receiving_notify reimburse hard_close].freeze
46
+ end
@@ -41,6 +41,7 @@ module Lunixi
41
41
  def create_checkout_intent(request, sellers, multi_seller_policy: MarketplaceMultiSellerPolicy::ALL_OR_NOTHING, idempotency_key: nil)
42
42
  body = split_body(payload!(request, 'create_checkout_intent request'), sellers, multi_seller_policy)
43
43
  OrderDetails.check!(body, 'A marketplace payment intent', checkout_intent: true)
44
+ RoutingPin.field!(body)
44
45
  response = @routes.call('createCheckoutIntent', body: body, idempotency_key: idempotency_key)
45
46
  intent = RouteResponse.merge_root(response)
46
47
  return response if RouteResponse.text(intent['token']) || RouteResponse.text(intent['checkoutFormContent'])
@@ -59,6 +60,7 @@ module Lunixi
59
60
  body = payload!(payload, 'charge_marketplace_card payload')
60
61
  charge_amount!(body)
61
62
  OrderDetails.check!(body, 'A marketplace card charge')
63
+ RoutingPin.field!(body, payment_method: PaymentMethod::CARD)
62
64
  @routes.call(three_ds ? 'chargeMarketplaceCard3d' : 'chargeMarketplaceCard2d', body: body, idempotency_key: idempotency_key)
63
65
  end
64
66
 
@@ -6,7 +6,7 @@ module Lunixi
6
6
  # Local checks of the payment-link bodies (list filters: PaymentLinkFilters; image uploads:
7
7
  # PaymentLinkImageRules).
8
8
  module PaymentLinkRules
9
- CREATE_FIELDS = (['environment'] + PAYMENT_LINK_SPEC_FIELDS).freeze
9
+ CREATE_FIELDS = (PAYMENT_LINK_CREATE_ONLY_FIELDS + PAYMENT_LINK_SPEC_FIELDS).freeze
10
10
  UPDATE_FIELDS = PAYMENT_LINK_SPEC_FIELDS
11
11
  TIME_FIELDS = %w[startsAt expiresAt eventAt].freeze
12
12
  LINK_ACTIONS = %w[pause resume deactivate].freeze
@@ -18,6 +18,7 @@ module Lunixi
18
18
  def create_body!(body)
19
19
  data = root!(body, 'Payment link request')
20
20
  known!(data, CREATE_FIELDS, 'create')
21
+ checkout_routing!(data)
21
22
  times(data)
22
23
  end
23
24
 
@@ -30,9 +31,20 @@ module Lunixi
30
31
  raise ConfigurationError, "'#{fixed}' is fixed when a payment link is created and cannot be updated; create a new link instead" if fixed
31
32
 
32
33
  known!(data, UPDATE_FIELDS, 'update')
34
+ checkout_routing!(data)
33
35
  times(data)
34
36
  end
35
37
 
38
+ # checkout.routing, when given, is a routing pin (routing is not a top-level link field). The pin
39
+ # must be in the link's environment (otherwise 400 payment.routing.pin_mismatch, details.mismatch
40
+ # ENVIRONMENT); a target in maintenance or inactive does not stop the link (a STRICT pin is checked
41
+ # when the buyer pays).
42
+ def checkout_routing!(data)
43
+ return unless data['checkout'].is_a?(Hash)
44
+
45
+ data['checkout'] = RoutingPin.field!(data['checkout'].transform_keys(&:to_s), 'checkout.routing')
46
+ end
47
+
36
48
  # pause / resume / deactivate body: expectedRowVersion (optional) and reason.
37
49
  def action_body!(action, expected_row_version, reason)
38
50
  raise ConfigurationError, "Payment link action must be one of #{LINK_ACTIONS.join(', ')}" unless LINK_ACTIONS.include?(action.to_s)
@@ -118,6 +118,10 @@ module Lunixi
118
118
  ALL = [PNG, JPEG, WEBP].freeze
119
119
  end
120
120
 
121
+ # Fields a create body may carry besides PAYMENT_LINK_SPEC_FIELDS: environment. An update does not
122
+ # take it. The routing pin of a link is checkout.routing (create and update).
123
+ PAYMENT_LINK_CREATE_ONLY_FIELDS = %w[environment].freeze
124
+
121
125
  # Every field of a payment-link definition in the gateway's spelling. Create and update bodies may
122
126
  # carry only these keys (plus environment on create); the gateway rejects any other key with 400.
123
127
  PAYMENT_LINK_SPEC_FIELDS = %w[
@@ -24,7 +24,9 @@ module Lunixi
24
24
 
25
25
  # Create a link. The idempotency key is required: the same key with the same body returns the stored
26
26
  # link with replayed: true; the same key with another body is 409 payment_link.idempotency.conflict.
27
- # Only PAYMENT_LINK_SPEC_FIELDS and environment are accepted; amounts are minor-unit strings.
27
+ # Only PAYMENT_LINK_SPEC_FIELDS and PAYMENT_LINK_CREATE_ONLY_FIELDS are accepted; amounts are
28
+ # minor-unit strings. checkout.routing pins every payment of the link (create and update; a
29
+ # connection in another environment than the link is refused with 400).
28
30
  def create(body, idempotency_key: nil)
29
31
  client.request('POST', BASE, body: PaymentLinkRules.create_body!(body), idempotency_key: Client.idempotency_key!(idempotency_key))
30
32
  end