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
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- module Lunixi
3
+ module Lunixi # rubocop:disable Metrics/ModuleLength -- one constant group per catalog value set
4
4
  # Sanctions screening values and routes (/api/v1/sanction, product SANCTION_SERVICE).
5
5
 
6
6
  # Risk domains a screening can be narrowed to (riskDomains). Omitted: every domain.
@@ -56,6 +56,240 @@ module Lunixi
56
56
  ALL = [EXACT, PROBABLE, POSSIBLE].freeze
57
57
  end
58
58
 
59
+ # Why a screening's coverage is not COMPLETE (coverageReasons). JURISDICTION_LISTS_UNAVAILABLE is
60
+ # informational: the country risk lists could not be read, so the country was not assessed; the name
61
+ # result and coverageStatus are unchanged.
62
+ module SanctionCoverageReason
63
+ NO_APPLICABLE_DOMAIN = 'NO_APPLICABLE_DOMAIN'
64
+ DOMAIN_NOT_PUBLISHED = 'DOMAIN_NOT_PUBLISHED'
65
+ DATASET_NOT_PUBLISHED = 'DATASET_NOT_PUBLISHED'
66
+ JURISDICTION_LISTS_UNAVAILABLE = 'JURISDICTION_LISTS_UNAVAILABLE'
67
+ ALL = [NO_APPLICABLE_DOMAIN, DOMAIN_NOT_PUBLISHED, DATASET_NOT_PUBLISHED, JURISDICTION_LISTS_UNAVAILABLE].freeze
68
+ end
69
+
70
+ # Country risk lists of name screening (jurisdictionRisk). The subject's countries (country,
71
+ # nationality, residenceCountry, registrationCountry) are compared with each list one by one.
72
+ # FATF_CALL_FOR_ACTION (effect REVIEW) turns an allow into a review; FATF_INCREASED_MONITORING and
73
+ # EU_HIGH_RISK_THIRD_COUNTRIES (EU Delegated Regulation 2016/1675) are information only (INFO). A
74
+ # country never blocks on its own.
75
+ module SanctionJurisdictionListCode
76
+ FATF_CALL_FOR_ACTION = 'FATF_CALL_FOR_ACTION'
77
+ FATF_INCREASED_MONITORING = 'FATF_INCREASED_MONITORING'
78
+ EU_HIGH_RISK_THIRD_COUNTRIES = 'EU_HIGH_RISK_THIRD_COUNTRIES'
79
+ ALL = [FATF_CALL_FOR_ACTION, FATF_INCREASED_MONITORING, EU_HIGH_RISK_THIRD_COUNTRIES].freeze
80
+ end
81
+
82
+ # Effect of a country risk match; jurisdictionRisk.effect is the strongest, NONE without a match.
83
+ module SanctionJurisdictionRiskEffect
84
+ REVIEW = 'REVIEW'
85
+ INFO = 'INFO'
86
+ NONE = 'NONE'
87
+ ALL = [REVIEW, INFO, NONE].freeze
88
+ end
89
+
90
+ # ASSESSED: a country was compared; NO_COUNTRY: none was given; UNAVAILABLE: the lists were not read.
91
+ module SanctionJurisdictionRiskStatus
92
+ ASSESSED = 'ASSESSED'
93
+ NO_COUNTRY = 'NO_COUNTRY'
94
+ UNAVAILABLE = 'UNAVAILABLE'
95
+ ALL = [ASSESSED, NO_COUNTRY, UNAVAILABLE].freeze
96
+ end
97
+
98
+ # Why a website hit matched: the listed host itself (EXACT_HOST, score 100) or a subdomain of it
99
+ # (PARENT_DOMAIN, score 80).
100
+ module SanctionWebsiteMatchType
101
+ EXACT_HOST = 'EXACT_HOST'
102
+ PARENT_DOMAIN = 'PARENT_DOMAIN'
103
+ ALL = [EXACT_HOST, PARENT_DOMAIN].freeze
104
+ end
105
+
106
+ # Bulk screening job states: DRAFT … COMPLETED, or FAILED (failureCode), CANCELLED, ERASED.
107
+ module SanctionBatchStatus
108
+ DRAFT = 'DRAFT'
109
+ UPLOADED = 'UPLOADED'
110
+ VALIDATING = 'VALIDATING'
111
+ VALIDATED = 'VALIDATED'
112
+ QUEUED = 'QUEUED'
113
+ RUNNING = 'RUNNING'
114
+ REPORTING = 'REPORTING'
115
+ COMPLETED = 'COMPLETED'
116
+ FAILED = 'FAILED'
117
+ CANCELLED = 'CANCELLED'
118
+ ERASED = 'ERASED'
119
+ ALL = [
120
+ DRAFT,
121
+ UPLOADED,
122
+ VALIDATING,
123
+ VALIDATED,
124
+ QUEUED,
125
+ RUNNING,
126
+ REPORTING,
127
+ COMPLETED,
128
+ FAILED,
129
+ CANCELLED,
130
+ ERASED
131
+ ].freeze
132
+ end
133
+
134
+ # Decision of a bulk screening row or hit.
135
+ module SanctionBatchDecision
136
+ BLOCK = 'block'
137
+ REVIEW = 'review'
138
+ ALLOW = 'allow'
139
+ ALL = [BLOCK, REVIEW, ALLOW].freeze
140
+ end
141
+
142
+ # Row status in the bulk screening results.
143
+ module SanctionBatchRowStatus
144
+ SCREENED = 'SCREENED'
145
+ INVALID = 'INVALID'
146
+ ERROR = 'ERROR'
147
+ ALL = [SCREENED, INVALID, ERROR].freeze
148
+ end
149
+
150
+ # Result tier: a hit on a headline group, or on any other list in scope.
151
+ module SanctionBatchTier
152
+ HEADLINE = 'HEADLINE'
153
+ OTHER = 'OTHER'
154
+ ALL = [HEADLINE, OTHER].freeze
155
+ end
156
+
157
+ # Report formats; PDF takes the language from lang, then Accept-Language, then Turkish.
158
+ module SanctionBatchReportFormat
159
+ PDF = 'pdf'
160
+ PDF_TR = 'pdf_tr'
161
+ PDF_EN = 'pdf_en'
162
+ XLSX = 'xlsx'
163
+ CSV = 'csv'
164
+ ALL = [PDF, PDF_TR, PDF_EN, XLSX, CSV].freeze
165
+ end
166
+
167
+ # Fields a file column can be mapped to; also identifier:<type> (at most four).
168
+ module SanctionBatchMappingField
169
+ NAME = 'name'
170
+ SUBJECT_TYPE = 'subjectType'
171
+ DATE_OF_BIRTH = 'dateOfBirth'
172
+ COUNTRY = 'country'
173
+ TCKN = 'tckn'
174
+ VKN = 'vkn'
175
+ PASSPORT = 'passport'
176
+ CUSTOMER_REFERENCE = 'customerReference'
177
+ # Country risk only (ISO code or country name, resolved to the ISO code).
178
+ NATIONALITY = 'nationality'
179
+ RESIDENCE_COUNTRY = 'residenceCountry'
180
+ REGISTRATION_COUNTRY = 'registrationCountry'
181
+ ALL = [
182
+ NAME, SUBJECT_TYPE, DATE_OF_BIRTH, COUNTRY, TCKN, VKN, PASSPORT, CUSTOMER_REFERENCE,
183
+ NATIONALITY, RESIDENCE_COUNTRY, REGISTRATION_COUNTRY
184
+ ].freeze
185
+ end
186
+
187
+ # Why a decision was reached for a bulk screening row or hit.
188
+ module SanctionBatchReasonCode
189
+ BLOCK_IDENTIFIER_MATCH = 'BLOCK_IDENTIFIER_MATCH'
190
+ BLOCK_EXACT_NAME_DOB = 'BLOCK_EXACT_NAME_DOB'
191
+ REVIEW_EXACT_NAME_UNCONFIRMED = 'REVIEW_EXACT_NAME_UNCONFIRMED'
192
+ REVIEW_SIMILARITY = 'REVIEW_SIMILARITY'
193
+ # The subject's country is on the FATF call-for-action list.
194
+ REVIEW_HIGH_RISK_JURISDICTION = 'REVIEW_HIGH_RISK_JURISDICTION'
195
+ ALLOW_BELOW_THRESHOLD = 'ALLOW_BELOW_THRESHOLD'
196
+ ALL = [
197
+ BLOCK_IDENTIFIER_MATCH,
198
+ BLOCK_EXACT_NAME_DOB,
199
+ REVIEW_EXACT_NAME_UNCONFIRMED,
200
+ REVIEW_SIMILARITY,
201
+ REVIEW_HIGH_RISK_JURISDICTION,
202
+ ALLOW_BELOW_THRESHOLD
203
+ ].freeze
204
+ end
205
+
206
+ # Why a bulk screening job ended FAILED (failureCode).
207
+ module SanctionBatchFailureCode
208
+ INPUT_UNREADABLE = 'INPUT_UNREADABLE'
209
+ INPUT_LIMIT_EXCEEDED = 'INPUT_LIMIT_EXCEEDED'
210
+ NO_VALID_ROWS = 'NO_VALID_ROWS'
211
+ LIST_STALE = 'LIST_STALE'
212
+ PIN_LOST = 'PIN_LOST'
213
+ COVERAGE_PARTIAL = 'COVERAGE_PARTIAL'
214
+ COVERAGE_DEGRADED_RATE = 'COVERAGE_DEGRADED_RATE'
215
+ ERROR_RATE_EXCEEDED = 'ERROR_RATE_EXCEEDED'
216
+ INVARIANT_BROKEN = 'INVARIANT_BROKEN'
217
+ REPORT_LEAK_BLOCKED = 'REPORT_LEAK_BLOCKED'
218
+ INTERNAL = 'INTERNAL'
219
+ ALL = [
220
+ INPUT_UNREADABLE,
221
+ INPUT_LIMIT_EXCEEDED,
222
+ NO_VALID_ROWS,
223
+ LIST_STALE,
224
+ PIN_LOST,
225
+ COVERAGE_PARTIAL,
226
+ COVERAGE_DEGRADED_RATE,
227
+ ERROR_RATE_EXCEEDED,
228
+ INVARIANT_BROKEN,
229
+ REPORT_LEAK_BLOCKED,
230
+ INTERNAL
231
+ ].freeze
232
+ end
233
+
234
+ # Why a bulk screening row was not screened (invalidReason).
235
+ module SanctionBatchInvalidReason
236
+ NAME_EMPTY = 'NAME_EMPTY'
237
+ NAME_TOO_LONG = 'NAME_TOO_LONG'
238
+ SUBJECT_TYPE_INVALID = 'SUBJECT_TYPE_INVALID'
239
+ DOB_INVALID = 'DOB_INVALID'
240
+ COUNTRY_INVALID = 'COUNTRY_INVALID'
241
+ TCKN_INVALID = 'TCKN_INVALID'
242
+ VKN_INVALID = 'VKN_INVALID'
243
+ IDENTIFIER_TOO_SHORT = 'IDENTIFIER_TOO_SHORT'
244
+ IDENTIFIER_TYPE_INVALID = 'IDENTIFIER_TYPE_INVALID'
245
+ TOO_MANY_IDENTIFIERS = 'TOO_MANY_IDENTIFIERS'
246
+ CUSTOMER_REFERENCE_TOO_LONG = 'CUSTOMER_REFERENCE_TOO_LONG'
247
+ ROW_UNREADABLE = 'ROW_UNREADABLE'
248
+ ALL = [
249
+ NAME_EMPTY,
250
+ NAME_TOO_LONG,
251
+ SUBJECT_TYPE_INVALID,
252
+ DOB_INVALID,
253
+ COUNTRY_INVALID,
254
+ TCKN_INVALID,
255
+ VKN_INVALID,
256
+ IDENTIFIER_TOO_SHORT,
257
+ IDENTIFIER_TYPE_INVALID,
258
+ TOO_MANY_IDENTIFIERS,
259
+ CUSTOMER_REFERENCE_TOO_LONG,
260
+ ROW_UNREADABLE
261
+ ].freeze
262
+ end
263
+
264
+ # How a bulk screening estimate was priced.
265
+ module SanctionBatchPricingSource
266
+ PLAN_UNIT_FEE = 'PLAN_UNIT_FEE'
267
+ UNPRICED = 'UNPRICED'
268
+ UNLIMITED = 'UNLIMITED'
269
+ NO_ACCESS = 'NO_ACCESS'
270
+ ALL = [PLAN_UNIT_FEE, UNPRICED, UNLIMITED, NO_ACCESS].freeze
271
+ end
272
+
273
+ # Sanction webhook event types. The bulk screening events carry batchId; their event id is <type>:<batchId>.
274
+ module SanctionEvents
275
+ MATCH_DETECTED = 'screening.match.detected'
276
+ FALSE_POSITIVE_CLEARED = 'screening.false_positive.cleared'
277
+ MONITORING_ALERT_CREATED = 'ongoing_monitoring.alert.created'
278
+ MONITORING_CLEAR = 'ongoing_monitoring.clear'
279
+ BATCH_SCREENING_COMPLETED = 'sanction.batch_screening.completed'
280
+ BATCH_SCREENING_FAILED = 'sanction.batch_screening.failed'
281
+ BATCH_SCREENING_ERASED = 'sanction.batch_screening.erased'
282
+ # A monitored subject's country was added to the FATF call-for-action list (monitoredEntityId,
283
+ # externalCustomerId, subjectName, fields, country, listCode, listName, listDate, listVersionId,
284
+ # screeningRequestId, detectedAt, caseId, severity).
285
+ MONITORING_JURISDICTION_RISK_FOUND = 'sanction.monitoring.jurisdiction_risk_found'
286
+ ALL = [
287
+ MATCH_DETECTED, FALSE_POSITIVE_CLEARED, MONITORING_ALERT_CREATED, MONITORING_CLEAR,
288
+ BATCH_SCREENING_COMPLETED, BATCH_SCREENING_FAILED, BATCH_SCREENING_ERASED,
289
+ MONITORING_JURISDICTION_RISK_FOUND
290
+ ].freeze
291
+ end
292
+
59
293
  sanction_page = %w[limit cursor].freeze
60
294
 
61
295
  # Every sanction route an API key can reach: method, path, whether it is a screening (the answer must
@@ -66,9 +300,12 @@ module Lunixi
66
300
  SANCTION_ROUTES = {
67
301
  'screenName' => RouteRequest.route('POST', '/api/v1/sanction/screening/name',
68
302
  screening: true, required: %w[name],
69
- optional: %w[subjectType country dateOfBirth identifiers riskDomains mode threshold customerReference]),
303
+ optional: %w[subjectType country dateOfBirth identifiers riskDomains mode threshold customerReference
304
+ nationality residenceCountry registrationCountry]),
70
305
  'screenWallet' => RouteRequest.route('POST', '/api/v1/sanction/screening/wallet',
71
306
  screening: true, required: %w[walletAddress], optional: %w[chain mode customerReference]),
307
+ 'screenWebsite' => RouteRequest.route('POST', '/api/v1/sanction/screening/website',
308
+ screening: true, required: %w[website], optional: %w[customerReference]),
72
309
  'screenAccount' => RouteRequest.route('POST', '/api/v1/sanction/screening/account',
73
310
  screening: true, required: %w[accountValue accountScheme],
74
311
  optional: %w[providerCode productChannel customerReference]),
@@ -108,7 +345,43 @@ module Lunixi
108
345
  'getOwnershipAggregation' => RouteRequest.route('GET', '/api/v1/sanction/intelligence/ownership-aggregation/:entityId',
109
346
  screening: false, query: %w[depth entityIds]),
110
347
 
111
- 'listBlacklistEntries' => RouteRequest.route('GET', '/api/v1/sanction/blacklist', screening: false, query: sanction_page)
348
+ 'listBlacklistEntries' => RouteRequest.route('GET', '/api/v1/sanction/blacklist', screening: false, query: sanction_page),
349
+ # Bulk screening: writes need sanction:batch_screen and X-Actor-Id (actorId), reads sanction:batch_view.
350
+ 'listCatalog' => RouteRequest.route('GET', '/api/v1/sanction/lists',
351
+ screening: false, query: %w[riskDomain]),
352
+ 'createBatch' => RouteRequest.route('POST', '/api/v1/sanction/batches',
353
+ screening: false, actor_id: true, idempotency_key: true, required: %w[name],
354
+ optional: %w[retentionDays defaultSubjectType listScope headlineGroups]),
355
+ 'createBatchUploadSession' => RouteRequest.route('POST', '/api/v1/sanction/batches/:batchId/upload-session',
356
+ screening: false, actor_id: true, required: %w[fileName contentType bytes sha256], optional: []),
357
+ 'completeBatchUpload' => RouteRequest.route('POST', '/api/v1/sanction/batches/:batchId/upload-complete',
358
+ screening: false, actor_id: true, required: %w[uploadId parts], optional: []),
359
+ 'appendBatchRows' => RouteRequest.route('POST', '/api/v1/sanction/batches/:batchId/rows',
360
+ screening: false, actor_id: true, required: %w[chunkNo rows], optional: []),
361
+ 'setBatchColumnMapping' => RouteRequest.route('POST', '/api/v1/sanction/batches/:batchId/column-mapping',
362
+ screening: false, actor_id: true, required: %w[mapping], optional: %w[defaultSubjectType]),
363
+ 'getBatchValidation' => RouteRequest.route('GET', '/api/v1/sanction/batches/:batchId/validation',
364
+ screening: false),
365
+ 'getBatchEstimate' => RouteRequest.route('GET', '/api/v1/sanction/batches/:batchId/estimate',
366
+ screening: false),
367
+ 'submitBatch' => RouteRequest.route('POST', '/api/v1/sanction/batches/:batchId/submit',
368
+ screening: false, actor_id: true, required: %w[confirmEstimate estimateAmountMinor], optional: []),
369
+ 'cancelBatch' => RouteRequest.route('POST', '/api/v1/sanction/batches/:batchId/cancel',
370
+ screening: false, actor_id: true, required: [], optional: %w[reason]),
371
+ 'listBatches' => RouteRequest.route('GET', '/api/v1/sanction/batches',
372
+ screening: false, query: %w[limit cursor status]),
373
+ 'getBatch' => RouteRequest.route('GET', '/api/v1/sanction/batches/:batchId',
374
+ screening: false),
375
+ 'listBatchResults' => RouteRequest.route('GET', '/api/v1/sanction/batches/:batchId/results',
376
+ screening: false, query: %w[limit cursor decision tier group listId basis customerReference status]),
377
+ 'getBatchResultRow' => RouteRequest.route('GET', '/api/v1/sanction/batches/:batchId/results/:rowNo',
378
+ screening: false),
379
+ 'getBatchReportUrl' => RouteRequest.route('GET', '/api/v1/sanction/batches/:batchId/reports/:format',
380
+ screening: false, query: %w[lang]),
381
+ 'eraseBatch' => RouteRequest.route('DELETE', '/api/v1/sanction/batches/:batchId',
382
+ screening: false, actor_id: true, required: [], optional: %w[reason]),
383
+ 'getBatchErasureCertificate' => RouteRequest.route('GET', '/api/v1/sanction/batches/:batchId/erasure-certificate',
384
+ screening: false)
112
385
  }.freeze
113
386
 
114
387
  # Fields of the nested lists, checked element by element ("route.field").
@@ -117,7 +390,14 @@ module Lunixi
117
390
  'screenTransaction.parties' => {
118
391
  'required' => %w[name].freeze, 'optional' => %w[role subjectType countryCode customerId dateOfBirth nationalId].freeze
119
392
  }.freeze,
120
- 'screenTransaction.accounts' => { 'required' => %w[accountType value].freeze, 'optional' => %w[role providerCode chain].freeze }.freeze
393
+ 'screenTransaction.accounts' => { 'required' => %w[accountType value].freeze, 'optional' => %w[role providerCode chain].freeze }.freeze,
394
+ 'createBatch.headlineGroups' => { 'required' => %w[id listIds].freeze, 'optional' => %w[labelTr labelEn].freeze }.freeze,
395
+ 'completeBatchUpload.parts' => { 'required' => %w[partNo etag].freeze, 'optional' => [].freeze }.freeze,
396
+ 'appendBatchRows.rows' => {
397
+ 'required' => %w[name].freeze,
398
+ 'optional' => %w[subjectType dateOfBirth country identifiers customerReference
399
+ nationality residenceCountry registrationCountry].freeze
400
+ }.freeze
121
401
  }.freeze
122
402
 
123
403
  # Value sets checked before sending ("route.field"); the sanction service refuses anything else with 400.
@@ -127,6 +407,10 @@ module Lunixi
127
407
  'screenName.subjectType' => SanctionSubjectType::ALL,
128
408
  'screenWallet.mode' => SanctionWalletScreenMode::ALL,
129
409
  'registerMonitoring.subjectType' => SanctionSubjectType::ALL,
130
- 'registerMonitoring.riskDomainScope' => SanctionRiskDomain::ALL
410
+ 'registerMonitoring.riskDomainScope' => SanctionRiskDomain::ALL,
411
+ 'createBatch.defaultSubjectType' => SanctionSubjectType::ALL,
412
+ # A row's subject type; the gateway checks it (listed for the catalog).
413
+ 'appendBatchRows.rows.subjectType' => SanctionSubjectType::ALL,
414
+ 'setBatchColumnMapping.defaultSubjectType' => SanctionSubjectType::ALL
131
415
  }.freeze
132
416
  end
@@ -11,7 +11,8 @@ module Lunixi
11
11
  buyer billingAddress shippingAddress basketItems].freeze
12
12
 
13
13
  # Fields of one split leg.
14
- SPLIT_PAYMENT_LEG_FIELDS = (%w[paymentMethod cardToken amount force3D installment installmentQuoteToken] + SPLIT_LEG_BLOCK_FIELDS).freeze
14
+ SPLIT_PAYMENT_LEG_FIELDS = (%w[paymentMethod cardToken card cardRewardSelection amount force3D installment installmentQuoteToken
15
+ routing] + SPLIT_LEG_BLOCK_FIELDS).freeze
15
16
 
16
17
  # Filters of payments.list_splits (GET /payments/split).
17
18
  LIST_SPLIT_PAYMENTS_FILTERS = %w[status currency createdFrom createdTo orderId ownerRef limit after].freeze
@@ -77,9 +78,23 @@ module Lunixi
77
78
  block = SPLIT_LEG_BLOCK_FIELDS.find { |field| !leg[field].nil? }
78
79
  raise ConfigurationError, "#{path} is a card leg and cannot carry the '#{block}' block" if block
79
80
 
81
+ if leg.key?('cardRewardSelection')
82
+ value = leg['cardRewardSelection']
83
+ unless value.is_a?(Hash) && value.keys.sort == %w[amountMinor
84
+ selectionId] && value['selectionId'].is_a?(String) && value['selectionId'].length == 36 &&
85
+ leg['card'].is_a?(Hash) && leg['card']['cardNumber'] && !leg['cardToken'] && leg['force3D'] != true
86
+ raise ConfigurationError, "#{path}: reward selection requires a new-card 2D sale"
87
+ end
88
+
89
+ Money.minor(value['amountMinor'], positive: true)
90
+ end
91
+ RoutingPin.field!(leg, "#{path}.routing", payment_method: PaymentMethod::CARD)
80
92
  return
81
93
  end
82
- method_leg!(leg, path, MethodFields.normalize_payment_method(method))
94
+ code = MethodFields.normalize_payment_method(method)
95
+ method_leg!(leg, path, code)
96
+ block = leg[MethodFields.block_name_of(code)]
97
+ RoutingPin.field!(leg, "#{path}.routing", payment_method: code, block_provider_code: block['providerCode'])
83
98
  end
84
99
 
85
100
  # Query of GET /payments/split; status and currency may be a value or a list (repeated parameters).
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # routing of a subscription with a pin (SUBSCRIPTION_ROUTING_FIELDS): the pin of its charges
5
+ # (requested, given fields only) and, while the charges are stopped by the pin, the block (block_code
6
+ # payment.routing.*, block_reason a RoutingPinReason value or nil, blocked_at ISO 8601).
7
+ class SubscriptionRouting
8
+ attr_reader :requested, :block_code, :block_reason, :blocked_at, :raw
9
+
10
+ # routing of a subscription (or of a response's data), or nil without a pin.
11
+ def self.from_subscription(subscription)
12
+ data = subscription.is_a?(Hash) && subscription.key?('data') ? subscription['data'] : subscription
13
+ routing = data.is_a?(Hash) ? data['routing'] : nil
14
+ routing.is_a?(Hash) ? new(routing.transform_keys(&:to_s)) : nil
15
+ end
16
+
17
+ # The given fields of a pin Hash (providerCode, credentialId, mode).
18
+ def self.pin_of(value)
19
+ return {} unless value.is_a?(Hash)
20
+
21
+ value.transform_keys(&:to_s).slice(*ROUTING_PIN_FIELDS).select { |_, entry| entry.is_a?(String) && !entry.empty? }
22
+ end
23
+
24
+ def initialize(data)
25
+ @raw = data.freeze
26
+ @requested = self.class.pin_of(data['requested']).freeze
27
+ block = data['blocked'].is_a?(Hash) ? data['blocked'].transform_keys(&:to_s) : nil
28
+ @blocked = !block.nil?
29
+ @block_code = block && text(block['code'])
30
+ @block_reason = block && text(block['reason'])
31
+ @blocked_at = block && text(block['at'])
32
+ end
33
+
34
+ # True while the charges are stopped by the pin.
35
+ def blocked?
36
+ @blocked
37
+ end
38
+
39
+ private
40
+
41
+ def text(value)
42
+ value.is_a?(String) && !value.empty? ? value : nil
43
+ end
44
+ end
45
+
46
+ # The data of a verified subscription.routing_pin_blocked webhook (SUBSCRIPTION_ROUTING_PIN_BLOCKED_FIELDS);
47
+ # raw keeps the whole data.
48
+ class SubscriptionRoutingPinBlocked
49
+ attr_reader :subscription_id, :invoice_id, :routing, :code, :reason, :blocked_at, :raw
50
+
51
+ # event_type and data of the verified event; another type raises ConfigurationError.
52
+ def self.from_event(event_type, data)
53
+ unless event_type == SubscriptionEvents::ROUTING_PIN_BLOCKED
54
+ raise ConfigurationError, "Expected a '#{SubscriptionEvents::ROUTING_PIN_BLOCKED}' event, got '#{event_type}'"
55
+ end
56
+
57
+ new(data.is_a?(Hash) ? data.transform_keys(&:to_s) : {})
58
+ end
59
+
60
+ def initialize(data)
61
+ @raw = data.freeze
62
+ @subscription_id = data['subscriptionId'].to_s
63
+ @invoice_id = data['invoiceId'].to_s
64
+ @routing = SubscriptionRouting.pin_of(data['routing']).freeze
65
+ @code = data['code'].to_s
66
+ @reason = data['reason'].is_a?(String) && !data['reason'].empty? ? data['reason'] : nil
67
+ @blocked_at = data['blockedAt'].is_a?(String) && !data['blockedAt'].empty? ? data['blockedAt'] : nil
68
+ end
69
+ end
70
+ end
@@ -1,6 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- module Lunixi
3
+ module Lunixi # rubocop:disable Metrics/ModuleLength -- one constant group per catalog value set
4
4
  # Subscription values and routes (/api/v1/subscriptions, and the portal-link routes under
5
5
  # /api/panel/v1/subscriptions/portal). The same codes as the Node and PHP SDKs.
6
6
 
@@ -106,8 +106,16 @@ module Lunixi
106
106
  PENDING_CHANGE_APPLIED = 'subscription.pending_change_applied'
107
107
  PAYMENT_CARD_SWAPPED = 'subscription.payment_card_swapped'
108
108
  PAYMENT_METHOD_LOST = 'subscription.payment_method_lost'
109
+ # A charge stopped because of the subscription's routing pin (a STRICT target cannot take it); data:
110
+ # SUBSCRIPTION_ROUTING_PIN_BLOCKED_FIELDS. The subscription waits in PAST_DUE (not canceled, not
111
+ # UNPAID) and the invoice is not retried automatically: change the pin with update_routing (the open
112
+ # invoice is charged again in the next retry round) or, once the connection is fixed, retry the
113
+ # invoice. Sent once per block.
114
+ ROUTING_PIN_BLOCKED = 'subscription.routing_pin_blocked'
109
115
  INVOICE_CREATED = 'invoice.created'
110
116
  INVOICE_PAID = 'invoice.paid'
117
+ # data.retryable false (with nextRetryAt nil): the charge stopped because of the routing pin and is
118
+ # not retried automatically.
111
119
  INVOICE_PAYMENT_FAILED = 'invoice.payment_failed'
112
120
  INVOICE_VOIDED = 'invoice.voided'
113
121
  CARD_ADDED = 'card.added'
@@ -117,7 +125,8 @@ module Lunixi
117
125
  CARD_EXPIRING_SOON = 'card.expiring_soon'
118
126
  CARD_EXPIRED = 'card.expired'
119
127
  ALL = [CREATED, ACTIVATED, TRIAL_WILL_END, PAUSED, RESUMED, CANCEL_SCHEDULED, CANCELED, UPGRADED, DOWNGRADED, PLAN_CHANGE_SCHEDULED,
120
- PENDING_CHANGE_APPLIED, PAYMENT_CARD_SWAPPED, PAYMENT_METHOD_LOST, INVOICE_CREATED, INVOICE_PAID, INVOICE_PAYMENT_FAILED,
128
+ PENDING_CHANGE_APPLIED, PAYMENT_CARD_SWAPPED, PAYMENT_METHOD_LOST, ROUTING_PIN_BLOCKED, INVOICE_CREATED, INVOICE_PAID,
129
+ INVOICE_PAYMENT_FAILED,
121
130
  INVOICE_VOIDED, CARD_ADDED, CARD_SET_DEFAULT, CARD_UPDATED, CARD_DEACTIVATED, CARD_EXPIRING_SOON, CARD_EXPIRED].freeze
122
131
  end
123
132
 
@@ -129,6 +138,17 @@ module Lunixi
129
138
  # Fields of a plan's billing rule.
130
139
  SUBSCRIPTION_BILLING_RULE_FIELDS = %w[frequency interval byMonthDay byWeekDay timezone lastDayOfMonthFix count].freeze
131
140
 
141
+ # Fields of a subscription's routing (only on a subscription with a pin): requested (the pin; a field
142
+ # not given is nil) and blocked (SUBSCRIPTION_ROUTING_BLOCK_FIELDS, or nil).
143
+ SUBSCRIPTION_ROUTING_FIELDS = %w[requested blocked].freeze
144
+
145
+ # Fields of routing.blocked: code (payment.routing.*), reason (a RoutingPinReason value or nil), at
146
+ # (ISO 8601).
147
+ SUBSCRIPTION_ROUTING_BLOCK_FIELDS = %w[code reason at].freeze
148
+
149
+ # Fields of the subscription.routing_pin_blocked event data.
150
+ SUBSCRIPTION_ROUTING_PIN_BLOCKED_FIELDS = %w[subscriptionId invoiceId routing code reason blockedAt].freeze
151
+
132
152
  subscriptions_base = '/api/v1/subscriptions'
133
153
  portal_panel = '/api/panel/v1/subscriptions/portal'
134
154
  cursor_query = %w[pageSize pageToken].freeze
@@ -144,7 +164,7 @@ module Lunixi
144
164
  'create' => route.call('POST', "#{subscriptions_base}/subscriptions",
145
165
  idempotency_key: 'required', required: %w[customerId planId idempotencyKey],
146
166
  optional: %w[paymentCardId paymentMethodId collectionMethod priceUpdatePolicy entitlementPolicy billingTimezone startsAt
147
- chargeOnCreate billingCycleAnchorOverride skipTrial metadata]),
167
+ chargeOnCreate billingCycleAnchorOverride skipTrial metadata routing]),
148
168
  'get' => route.call('GET', "#{subscriptions_base}/subscriptions/:subscriptionId"),
149
169
  'list' => route.call('GET', "#{subscriptions_base}/subscriptions", query: %w[customerId status] + cursor_query),
150
170
  'cancel' => route.call('POST', "#{subscriptions_base}/subscriptions/:subscriptionId/cancel", required: %w[cancelAtPeriodEnd], optional: %w[reason]),
@@ -152,6 +172,9 @@ module Lunixi
152
172
  'resume' => route.call('POST', "#{subscriptions_base}/subscriptions/:subscriptionId/resume"),
153
173
  'changePlan' => route.call('POST', "#{subscriptions_base}/subscriptions/:subscriptionId/change-plan",
154
174
  idempotency_key: 'optional', required: %w[newPlanId], optional: %w[behavior reason idempotencyKey]),
175
+ # routing nil removes the pin; the key is required (an empty body is 400).
176
+ 'updateRouting' => route.call('POST', "#{subscriptions_base}/subscriptions/:subscriptionId/routing",
177
+ required: %w[routing], optional: %w[reason]),
155
178
  'auditLogs' => route.call('GET', "#{subscriptions_base}/subscriptions/:subscriptionId/audit-logs", query: %w[limit pageToken]),
156
179
 
157
180
  'plans.create' => route.call('POST', "#{subscriptions_base}/plans",
@@ -60,8 +60,11 @@ module Lunixi
60
60
 
61
61
  # { customerId, planId, paymentCardId?, paymentMethodId?, collectionMethod?, priceUpdatePolicy?,
62
62
  # entitlementPolicy?, billingTimezone?, startsAt?, chargeOnCreate?, billingCycleAnchorOverride?,
63
- # skipTrial?, metadata? }. The Idempotency-Key is required (idempotency_key: or the request's
64
- # idempotencyKey; both given, they must agree) and is sent in the body as well.
63
+ # skipTrial?, metadata?, routing? }. The Idempotency-Key is required (idempotency_key: or the request's
64
+ # idempotencyKey; both given, they must agree) and is sent in the body as well. routing
65
+ # ({ providerCode:, credentialId:, mode: }) is stored on the subscription and sent with every period
66
+ # charge and retry; these charges have no 3D Secure step, so a STRICT target that needs it answers
67
+ # 422 payment.routing.pin_not_eligible and the charge is not retried daily.
65
68
  def create(request, idempotency_key: nil)
66
69
  body = RouteRequest.wire_hash!(request, 'create request')
67
70
  key = RouteTable.idempotency_key_of('create', body, idempotency_key)
@@ -71,6 +74,7 @@ module Lunixi
71
74
  SubscriptionRules.boolean!(body, 'skipTrial')
72
75
  raise ConfigurationError, "'metadata' must be a Hash." if body.key?('metadata') && !body['metadata'].is_a?(Hash)
73
76
 
77
+ RoutingPin.field!(body)
74
78
  @routes.data('create', body: body, idempotency_key: key)
75
79
  end
76
80
 
@@ -115,6 +119,22 @@ module Lunixi
115
119
  @routes.data('changePlan', params: { 'subscriptionId' => subscription_id }, body: body, idempotency_key: key)
116
120
  end
117
121
 
122
+ # Changes the routing pin of the subscription's charges (POST …/subscriptions/{id}/routing). routing
123
+ # is a pin Hash ({ providerCode:, credentialId:, mode: }) or nil to remove the pin (normal routing);
124
+ # reason (at most 500 characters) goes to the audit trail. The block mark is cleared and an open
125
+ # invoice held by the old pin is charged again in the next retry round. Returns the subscription
126
+ # (read its pin with Lunixi::SubscriptionRouting.from_subscription).
127
+ def update_routing(subscription_id, routing, reason: nil)
128
+ body = { 'routing' => routing.nil? ? nil : RoutingPin.pin!(routing) }
129
+ unless reason.nil? || reason == ''
130
+ raise ConfigurationError, 'reason must be a String' unless reason.is_a?(String)
131
+ raise ConfigurationError, 'reason must be at most 500 characters' if reason.length > 500
132
+
133
+ body['reason'] = reason
134
+ end
135
+ @routes.data('updateRouting', params: { 'subscriptionId' => subscription_id }, body: body, null_fields: %w[routing])
136
+ end
137
+
118
138
  # The audit trail of a subscription; filters limit, pageToken.
119
139
  def audit_logs(subscription_id, **filters)
120
140
  @routes.token_page('auditLogs', params: { 'subscriptionId' => subscription_id }, query: filters)
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Lunixi
4
- VERSION = '2.0.2'
4
+ VERSION = '2.3.0'
5
5
  end