lunixi-sdk 1.2.2 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +62 -0
  3. data/README.md +278 -10
  4. data/README.tr.md +282 -8
  5. data/docs/ruby.en.md +11 -1
  6. data/docs/ruby.tr.md +11 -1
  7. data/lib/lunixi/bank_connect.rb +340 -0
  8. data/lib/lunixi/bank_connect_filters.rb +114 -0
  9. data/lib/lunixi/bank_connect_values.rb +205 -0
  10. data/lib/lunixi/bank_transfer.rb +106 -0
  11. data/lib/lunixi/card_requests.rb +171 -0
  12. data/lib/lunixi/client.rb +57 -16
  13. data/lib/lunixi/direct_method_payment_request.rb +245 -0
  14. data/lib/lunixi/enabled_installments.rb +28 -0
  15. data/lib/lunixi/errors.rb +69 -3
  16. data/lib/lunixi/fraud.rb +81 -5
  17. data/lib/lunixi/identity.rb +94 -0
  18. data/lib/lunixi/identity_values.rb +28 -0
  19. data/lib/lunixi/insurance.rb +294 -0
  20. data/lib/lunixi/insurance_request.rb +134 -0
  21. data/lib/lunixi/insurance_values.rb +200 -0
  22. data/lib/lunixi/kyc.rb +189 -0
  23. data/lib/lunixi/kyc_values.rb +158 -0
  24. data/lib/lunixi/marketplace.rb +268 -0
  25. data/lib/lunixi/marketplace_values.rb +86 -0
  26. data/lib/lunixi/method_fields.rb +142 -0
  27. data/lib/lunixi/money.rb +7 -4
  28. data/lib/lunixi/order_details.rb +115 -0
  29. data/lib/lunixi/payment_link_filters.rb +32 -0
  30. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  31. data/lib/lunixi/payment_link_rules.rb +132 -0
  32. data/lib/lunixi/payment_link_values.rb +136 -0
  33. data/lib/lunixi/payment_links.rb +152 -0
  34. data/lib/lunixi/payment_values.rb +86 -0
  35. data/lib/lunixi/payments.rb +170 -8
  36. data/lib/lunixi/physical_pos.rb +183 -0
  37. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  38. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  39. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  40. data/lib/lunixi/physical_pos_filters.rb +58 -0
  41. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  42. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  43. data/lib/lunixi/physical_pos_management.rb +326 -0
  44. data/lib/lunixi/physical_pos_money.rb +46 -0
  45. data/lib/lunixi/physical_pos_request.rb +126 -0
  46. data/lib/lunixi/physical_pos_responses.rb +102 -0
  47. data/lib/lunixi/physical_pos_results.rb +52 -0
  48. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  49. data/lib/lunixi/physical_pos_value.rb +43 -0
  50. data/lib/lunixi/physical_pos_values.rb +203 -0
  51. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  52. data/lib/lunixi/product_webhooks.rb +106 -0
  53. data/lib/lunixi/promissory_note.rb +155 -0
  54. data/lib/lunixi/reference.rb +41 -0
  55. data/lib/lunixi/route_request.rb +121 -0
  56. data/lib/lunixi/route_response.rb +101 -0
  57. data/lib/lunixi/route_table.rb +128 -0
  58. data/lib/lunixi/route_value.rb +60 -0
  59. data/lib/lunixi/sanction.rb +244 -0
  60. data/lib/lunixi/sanction_values.rb +132 -0
  61. data/lib/lunixi/split_payment.rb +150 -0
  62. data/lib/lunixi/subscription_resources.rb +357 -0
  63. data/lib/lunixi/subscription_values.rb +233 -0
  64. data/lib/lunixi/subscriptions.rb +202 -0
  65. data/lib/lunixi/version.rb +1 -1
  66. data/lib/lunixi/wallet.rb +153 -0
  67. data/lib/lunixi/wallet_resources.rb +407 -0
  68. data/lib/lunixi/wallet_routes.rb +126 -0
  69. data/lib/lunixi/wallet_values.rb +71 -0
  70. data/lib/lunixi/wire_money.rb +67 -0
  71. data/lib/lunixi.rb +58 -0
  72. metadata +59 -1
@@ -0,0 +1,244 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Sanctions screening (/api/v1/sanction/*, product SANCTION_SERVICE).
5
+ #
6
+ # Calls carry the access token minted from your API key; these routes take no per-request signature.
7
+ # The key needs the sanction:view_results permission (403 otherwise).
8
+ #
9
+ # Screening returns matches, not verdicts: the decision is yours. Read a result with
10
+ # Lunixi::Sanction.clear_screening?(result): an empty match list is clear only when coverageStatus is
11
+ # COMPLETE. When the screening cannot run the gateway answers 503 (ApiError); a 2xx answer whose status
12
+ # is not "success" raises ApiError too. It never comes back as an empty result.
13
+ #
14
+ # Bodies and filters are checked against SANCTION_ROUTES before anything is sent: an unknown field, a
15
+ # missing required field, an empty anyOf group, a malformed nested row or a value outside its set
16
+ # (SANCTION_VALUE_SETS) raises ConfigurationError. Keys are the wire names (snake_case works too).
17
+ #
18
+ # Answers are the envelope's data. The envelope's requestId is the HTTP request's id; the screening's
19
+ # own id is data.screeningRequestId (name screening). Lists return a Lunixi::ListPage.
20
+ class Sanction
21
+ BLOCKING_DECISIONS = %w[block blocked reject rejected review hit escalate].freeze
22
+
23
+ # Whether a screening answer (the data a screen_* method returned) can be read as "nothing found":
24
+ # no match or hit of any kind, no listed or blocking flag, no blocking decision, and, when it reports
25
+ # coverage, coverageStatus COMPLETE. PARTIAL, DEGRADED or a nil coverage is never clear. Account and
26
+ # adverse-media screening report no coverage; for them the hits and flags decide.
27
+ def self.clear_screening?(result)
28
+ return false unless result.is_a?(Hash)
29
+ return false if %w[matches hits publicationHits].any? { |key| result[key].is_a?(Array) && !result[key].empty? }
30
+ return false if %w[isSanctioned isBlacklisted matched caseRequired].any? { |key| result[key] == true }
31
+ return false if result['decision'].is_a?(String) && BLOCKING_DECISIONS.include?(result['decision'].downcase)
32
+ return result['coverageStatus'] == SanctionCoverageStatus::COMPLETE if result.key?('coverageStatus')
33
+
34
+ true
35
+ end
36
+
37
+ def initialize(client)
38
+ @client = client
39
+ end
40
+
41
+ # Person or organization: { name, subjectType?, country?, dateOfBirth?, identifiers?, riskDomains?,
42
+ # mode?, threshold?, customerReference? }.
43
+ def screen_name(request)
44
+ screening('screenName', request)
45
+ end
46
+
47
+ # Crypto wallet address (exact match against the listed addresses).
48
+ def screen_wallet(request)
49
+ screening('screenWallet', request)
50
+ end
51
+
52
+ # Bank account / IBAN against your own deny list and account risk data (no list publication).
53
+ def screen_account(request)
54
+ screening('screenAccount', request)
55
+ end
56
+
57
+ # Every party and account of a transaction, against one list publication.
58
+ def screen_transaction(request)
59
+ screening('screenTransaction', request)
60
+ end
61
+
62
+ # Public procurement debarment lists, by name and TCKN / VKN. A list that is not published makes
63
+ # 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)
66
+ end
67
+
68
+ # Adverse media. Runs only when your adverse-media policy is enabled.
69
+ def screen_adverse_media(request)
70
+ screening('screenAdverseMedia', request)
71
+ end
72
+
73
+ # Behavioural risk signal evaluation.
74
+ def evaluate_behavioral_alert(request)
75
+ screening('evaluateBehavioralAlert', request)
76
+ end
77
+
78
+ # Earlier screenings (audit trail), newest first.
79
+ def list_screening_history(**filters)
80
+ page('listScreeningHistory', filters)
81
+ end
82
+
83
+ def iterate_screening_history(**filters, &block)
84
+ RouteResponse.each_item(filters, block) { |query| list_screening_history(**query) }
85
+ end
86
+
87
+ # Registers a subject for ongoing monitoring; returns { monitoredEntityId }. A profile Hash (name,
88
+ # dateOfBirth, country, identifiers ...) is sent as profileJson; pass one of the two.
89
+ def register_monitoring(request = {})
90
+ raise ConfigurationError, 'registerMonitoring request must be a Hash.' unless request.is_a?(Hash)
91
+
92
+ profile_key = request.keys.find { |key| key.to_s == 'profile' }
93
+ body = request
94
+ unless profile_key.nil?
95
+ body = request.reject { |key, _| key == profile_key }
96
+ if body.keys.any? { |key| %w[profileJson profile_json].include?(key.to_s) }
97
+ raise ConfigurationError, 'registerMonitoring takes profile or profileJson, not both.'
98
+ end
99
+
100
+ body = body.merge('profileJson' => JsonBody.dump(request[profile_key]))
101
+ end
102
+ RouteResponse.unwrap(invoke('registerMonitoring', body: body))
103
+ end
104
+
105
+ # New-match alerts raised by monitoring; status narrows (e.g. open).
106
+ def list_monitoring_alerts(**filters)
107
+ page('listMonitoringAlerts', filters)
108
+ end
109
+
110
+ def iterate_monitoring_alerts(**filters, &block)
111
+ RouteResponse.each_item(filters, block) { |query| list_monitoring_alerts(**query) }
112
+ end
113
+
114
+ # Monitored subjects; activeOnly defaults to true on the gateway.
115
+ def list_monitored_entities(**filters)
116
+ page('listMonitoredEntities', filters)
117
+ end
118
+
119
+ def iterate_monitored_entities(**filters, &block)
120
+ RouteResponse.each_item(filters, block) { |query| list_monitored_entities(**query) }
121
+ end
122
+
123
+ # Matches raised by monitoring.
124
+ def list_monitoring_matches(**filters)
125
+ page('listMonitoringMatches', filters)
126
+ end
127
+
128
+ def iterate_monitoring_matches(**filters, &block)
129
+ RouteResponse.each_item(filters, block) { |query| list_monitoring_matches(**query) }
130
+ end
131
+
132
+ # Freshness of the source lists: { manifest }. A manifest that could not be produced raises ApiError.
133
+ def get_dataset_freshness # rubocop:disable Naming/AccessorMethodName -- catalog operation getDatasetFreshness
134
+ checked(invoke('getDatasetFreshness'))
135
+ end
136
+
137
+ # Entity search by name: q, limit.
138
+ def search_entities(**filters)
139
+ RouteResponse.unwrap(invoke('searchEntities', query: filters))
140
+ end
141
+
142
+ # Entity risk profile; screening_request_id reads it on that screening's publication.
143
+ def get_entity_profile(entity_id, screening_request_id: nil)
144
+ entity('getEntityProfile', entity_id, 'screeningRequestId' => screening_request_id)
145
+ end
146
+
147
+ # Relationship graph, depth 1–3.
148
+ def get_entity_graph(entity_id, depth: nil)
149
+ entity('getEntityGraph', entity_id, 'depth' => depth)
150
+ end
151
+
152
+ # Indirect exposure paths; entity_ids are the records of a merged match (sent comma-separated).
153
+ def get_indirect_exposure(entity_id, max_depth: nil, entity_ids: nil)
154
+ entity('getIndirectExposure', entity_id, 'maxDepth' => max_depth, 'entityIds' => id_list(entity_ids))
155
+ end
156
+
157
+ # Ownership aggregation (50% rule); entity_ids are the records of a merged match.
158
+ def get_ownership_aggregation(entity_id, depth: nil, entity_ids: nil)
159
+ entity('getOwnershipAggregation', entity_id, 'depth' => depth, 'entityIds' => id_list(entity_ids))
160
+ end
161
+
162
+ # Your own deny-list entries (read only with an API key).
163
+ def list_blacklist_entries(**filters)
164
+ page('listBlacklistEntries', filters)
165
+ end
166
+
167
+ def iterate_blacklist_entries(**filters, &block)
168
+ RouteResponse.each_item(filters, block) { |query| list_blacklist_entries(**query) }
169
+ end
170
+
171
+ def inspect
172
+ '#<Lunixi::Sanction>'
173
+ end
174
+
175
+ private
176
+
177
+ def screening(name, request)
178
+ checked(invoke(name, body: request))
179
+ end
180
+
181
+ def page(name, filters)
182
+ RouteResponse.page(invoke(name, query: filters))
183
+ end
184
+
185
+ def entity(name, entity_id, query)
186
+ RouteResponse.unwrap(invoke(name, params: { 'entityId' => entity_id }, query: RouteRequest.compact(query)))
187
+ end
188
+
189
+ # Sends one route of SANCTION_ROUTES with the access token (no request signature).
190
+ def invoke(name, params: {}, body: nil, query: nil)
191
+ route = SANCTION_ROUTES.fetch(name)
192
+ path = RouteRequest.path!(route['path'], params)
193
+ filters = RouteRequest.query!(query, route['query'] || [], name)
194
+ payload = route['method'] == 'GET' ? nil : body!(name, route, body || {})
195
+ @client.request(route['method'], path, body: payload, query: filters, signed: false)
196
+ end
197
+
198
+ def body!(name, route, body)
199
+ plain = RouteRequest.fields!(body, route['required'], route['optional'], name)
200
+ if route['anyOf']&.none? { |key| RouteRequest.present?(plain[key]) }
201
+ raise ConfigurationError, "#{name} requires at least one of #{route['anyOf'].join(', ')}."
202
+ end
203
+
204
+ plain.keys.each do |key|
205
+ nested = SANCTION_NESTED_FIELDS["#{name}.#{key}"]
206
+ plain[key] = rows!(plain[key], nested, "#{name}.#{key}") if nested
207
+ allowed = SANCTION_VALUE_SETS["#{name}.#{key}"]
208
+ values!(plain[key], allowed, "#{name}.#{key}") if allowed
209
+ end
210
+ plain
211
+ end
212
+
213
+ def rows!(rows, spec, label)
214
+ raise ConfigurationError, "'#{label}' must be an array." unless rows.is_a?(Array)
215
+
216
+ rows.each_with_index.map { |row, index| RouteRequest.fields!(row, spec['required'], spec['optional'], "#{label}[#{index}]") }
217
+ end
218
+
219
+ def values!(value, allowed, label)
220
+ outside = Array(value).reject { |entry| allowed.include?(entry) }
221
+ return if outside.empty?
222
+
223
+ raise ConfigurationError, "'#{label}' must be one of #{allowed.join(', ')}."
224
+ end
225
+
226
+ # A 2xx answer that is not status "success" is refused rather than read: a screening that did not run
227
+ # must never look like an empty result.
228
+ def checked(response)
229
+ if response.is_a?(Hash) && response['status'].is_a?(String) && response['status'] != 'success'
230
+ status = response['statusCode'].is_a?(Integer) ? response['statusCode'] : 0
231
+ raise ApiError.new(status: status, code: response['code'], request_id: response['requestId'], message: 'The screening did not complete.')
232
+ end
233
+
234
+ RouteResponse.unwrap(response)
235
+ end
236
+
237
+ def id_list(entity_ids)
238
+ return nil if entity_ids.nil?
239
+
240
+ ids = Array(entity_ids).map { |id| id.to_s.strip }.reject(&:empty?)
241
+ ids.empty? ? nil : ids.join(',')
242
+ end
243
+ end
244
+ end
@@ -0,0 +1,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Sanctions screening values and routes (/api/v1/sanction, product SANCTION_SERVICE).
5
+
6
+ # Risk domains a screening can be narrowed to (riskDomains). Omitted: every domain.
7
+ module SanctionRiskDomain
8
+ SANCTIONS = 'sanctions'
9
+ PEP = 'pep'
10
+ RCA = 'rca'
11
+ WANTED = 'wanted'
12
+ REGULATORY = 'regulatory'
13
+ DEBARMENT = 'debarment'
14
+ OWNERSHIP = 'ownership'
15
+ VESSEL = 'vessel'
16
+ SECURITIES = 'securities'
17
+ ALL = [SANCTIONS, PEP, RCA, WANTED, REGULATORY, DEBARMENT, OWNERSHIP, VESSEL, SECURITIES].freeze
18
+ end
19
+
20
+ # Name-screening presets. Sent with riskDomains, their intersection is screened.
21
+ module SanctionScreenMode
22
+ SANCTIONS_ONLY = 'sanctions_only'
23
+ SANCTIONS_PEP = 'sanctions_pep'
24
+ FULL_RISK = 'full_risk'
25
+ ALL = [SANCTIONS_ONLY, SANCTIONS_PEP, FULL_RISK].freeze
26
+ end
27
+
28
+ # Wallet-screening depth; the wider modes add exposure and crypto-intelligence hits.
29
+ module SanctionWalletScreenMode
30
+ WALLET_SANCTIONS = 'wallet_sanctions'
31
+ WALLET_RISK = 'wallet_risk'
32
+ WALLET_FULL_AML = 'wallet_full_aml'
33
+ ALL = [WALLET_SANCTIONS, WALLET_RISK, WALLET_FULL_AML].freeze
34
+ end
35
+
36
+ module SanctionSubjectType
37
+ PERSON = 'person'
38
+ ORGANIZATION = 'organization'
39
+ ALL = [PERSON, ORGANIZATION].freeze
40
+ end
41
+
42
+ # How much of the requested scope a screening covered. COMPLETE: every requested risk domain was
43
+ # screened. PARTIAL: some requested domain has no list (uncoveredRiskDomains, uncoveredSources); no
44
+ # match is clear only for what was screened. DEGRADED: the candidate search was limited; screen again.
45
+ module SanctionCoverageStatus
46
+ COMPLETE = 'COMPLETE'
47
+ PARTIAL = 'PARTIAL'
48
+ DEGRADED = 'DEGRADED'
49
+ ALL = [COMPLETE, PARTIAL, DEGRADED].freeze
50
+ end
51
+
52
+ module SanctionHitType
53
+ EXACT = 'exact'
54
+ PROBABLE = 'probable'
55
+ POSSIBLE = 'possible'
56
+ ALL = [EXACT, PROBABLE, POSSIBLE].freeze
57
+ end
58
+
59
+ sanction_page = %w[limit cursor].freeze
60
+
61
+ # Every sanction route an API key can reach: method, path, whether it is a screening (the answer must
62
+ # be status: "success" to be read), the body fields the gateway forwards (required / optional / anyOf:
63
+ # at least one of them present) and the query parameters. The same table as the Node SDK's
64
+ # SANCTION_ROUTES; the parity test compares it with the shared catalog. The gateway passes the body to
65
+ # the sanction service, which silently drops an unknown field, so the SDK refuses one before sending.
66
+ SANCTION_ROUTES = {
67
+ 'screenName' => RouteRequest.route('POST', '/api/v1/sanction/screening/name',
68
+ screening: true, required: %w[name],
69
+ optional: %w[subjectType country dateOfBirth identifiers riskDomains mode threshold customerReference]),
70
+ 'screenWallet' => RouteRequest.route('POST', '/api/v1/sanction/screening/wallet',
71
+ screening: true, required: %w[walletAddress], optional: %w[chain mode customerReference]),
72
+ 'screenAccount' => RouteRequest.route('POST', '/api/v1/sanction/screening/account',
73
+ screening: true, required: %w[accountValue accountScheme],
74
+ optional: %w[providerCode productChannel customerReference]),
75
+ # Neither parties nor accounts: the sanction service holds the transaction as not screenable.
76
+ 'screenTransaction' => RouteRequest.route('POST', '/api/v1/sanction/screening/transaction',
77
+ screening: true, required: [],
78
+ optional: %w[transactionType direction amount currency channel occurredAt parties accounts metadataJson],
79
+ any_of: %w[parties accounts]),
80
+ 'screenPublicProcurementBan' => RouteRequest.route('POST', '/api/v1/sanction/intelligence/public-procurement-ban',
81
+ screening: true, required: [],
82
+ optional: %w[entityName tckn vkn entityType onlyActive limit customerReference productChannel],
83
+ any_of: %w[entityName tckn vkn]),
84
+ 'screenAdverseMedia' => RouteRequest.route('POST', '/api/v1/sanction/intelligence/adverse-media',
85
+ screening: true, required: [],
86
+ optional: %w[entityName entityType tckn vkn countryCode limit onlyActive customerReference productChannel]),
87
+ 'evaluateBehavioralAlert' => RouteRequest.route('POST', '/api/v1/sanction/intelligence/behavioral-alert',
88
+ screening: true, required: [],
89
+ optional: %w[subjectReference customerReference productChannel velocityScore unusualPattern
90
+ countryRiskLevel metadataJson]),
91
+ 'listScreeningHistory' => RouteRequest.route('GET', '/api/v1/sanction/screening/history', screening: false, query: sanction_page),
92
+
93
+ 'registerMonitoring' => RouteRequest.route('POST', '/api/v1/sanction/monitoring/register',
94
+ screening: false, required: %w[externalCustomerId],
95
+ optional: %w[subjectType profileJson frequency riskDomainScope]),
96
+ 'listMonitoringAlerts' => RouteRequest.route('GET', '/api/v1/sanction/monitoring/alerts',
97
+ screening: false, query: %w[status] + sanction_page + %w[includeTotal]),
98
+ 'listMonitoredEntities' => RouteRequest.route('GET', '/api/v1/sanction/monitoring/entities',
99
+ screening: false, query: %w[activeOnly] + sanction_page + %w[includeTotal]),
100
+ 'listMonitoringMatches' => RouteRequest.route('GET', '/api/v1/sanction/monitoring/matches', screening: false, query: %w[status] + sanction_page),
101
+ 'getDatasetFreshness' => RouteRequest.route('GET', '/api/v1/sanction/monitoring/dataset-freshness', screening: false),
102
+
103
+ 'searchEntities' => RouteRequest.route('GET', '/api/v1/sanction/intelligence/entity-search', screening: false, query: %w[q limit]),
104
+ 'getEntityProfile' => RouteRequest.route('GET', '/api/v1/sanction/intelligence/entity-profiles/:entityId', screening: false, query: %w[screeningRequestId]),
105
+ 'getEntityGraph' => RouteRequest.route('GET', '/api/v1/sanction/intelligence/entity-graph/:entityId', screening: false, query: %w[depth]),
106
+ 'getIndirectExposure' => RouteRequest.route('GET', '/api/v1/sanction/intelligence/indirect-exposure/:entityId',
107
+ screening: false, query: %w[maxDepth entityIds]),
108
+ 'getOwnershipAggregation' => RouteRequest.route('GET', '/api/v1/sanction/intelligence/ownership-aggregation/:entityId',
109
+ screening: false, query: %w[depth entityIds]),
110
+
111
+ 'listBlacklistEntries' => RouteRequest.route('GET', '/api/v1/sanction/blacklist', screening: false, query: sanction_page)
112
+ }.freeze
113
+
114
+ # Fields of the nested lists, checked element by element ("route.field").
115
+ SANCTION_NESTED_FIELDS = {
116
+ 'screenName.identifiers' => { 'required' => %w[type value].freeze, 'optional' => [].freeze }.freeze,
117
+ 'screenTransaction.parties' => {
118
+ 'required' => %w[name].freeze, 'optional' => %w[role subjectType countryCode customerId dateOfBirth nationalId].freeze
119
+ }.freeze,
120
+ 'screenTransaction.accounts' => { 'required' => %w[accountType value].freeze, 'optional' => %w[role providerCode chain].freeze }.freeze
121
+ }.freeze
122
+
123
+ # Value sets checked before sending ("route.field"); the sanction service refuses anything else with 400.
124
+ SANCTION_VALUE_SETS = {
125
+ 'screenName.riskDomains' => SanctionRiskDomain::ALL,
126
+ 'screenName.mode' => SanctionScreenMode::ALL,
127
+ 'screenName.subjectType' => SanctionSubjectType::ALL,
128
+ 'screenWallet.mode' => SanctionWalletScreenMode::ALL,
129
+ 'registerMonitoring.subjectType' => SanctionSubjectType::ALL,
130
+ 'registerMonitoring.riskDomainScope' => SanctionRiskDomain::ALL
131
+ }.freeze
132
+ end
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Method blocks a non-card split leg can carry. Meal card, open banking, shopping loan and bank
5
+ # transfer cannot be split payment legs.
6
+ SPLIT_LEG_BLOCK_FIELDS = %w[mobileBilling wallet promissoryNote].freeze
7
+
8
+ # Fields of a split payment body (payments.split). buyer, billingAddress and basketItems are
9
+ # required, shippingAddress when a basket item is PHYSICAL (OrderDetails).
10
+ SPLIT_PAYMENT_FIELDS = %w[totalAmount currency ownerRef legs orderId ownerScope callbackUrl
11
+ buyer billingAddress shippingAddress basketItems].freeze
12
+
13
+ # Fields of one split leg.
14
+ SPLIT_PAYMENT_LEG_FIELDS = (%w[paymentMethod cardToken amount force3D installment installmentQuoteToken] + SPLIT_LEG_BLOCK_FIELDS).freeze
15
+
16
+ # Filters of payments.list_splits (GET /payments/split).
17
+ LIST_SPLIT_PAYMENTS_FILTERS = %w[status currency createdFrom createdTo orderId ownerRef limit after].freeze
18
+
19
+ # Put this key into a webhook endpoint's event types to also receive the events of each leg. It is
20
+ # not an event type and payment.* does not include it.
21
+ SPLIT_LEG_EVENTS_SUBSCRIPTION = 'payment.split.leg_events'
22
+
23
+ # Status of a split payment (status).
24
+ module SplitPaymentStatus
25
+ COMPOSING = 'COMPOSING'
26
+ AUTHORIZING = 'AUTHORIZING'
27
+ AWAITING_3DS = 'AWAITING_3DS'
28
+ AWAITING_ACTION = 'AWAITING_ACTION'
29
+ AWAITING_CREDIT_APPROVAL = 'AWAITING_CREDIT_APPROVAL'
30
+ AWAITING_REPLACEMENT_CARD = 'AWAITING_REPLACEMENT_CARD'
31
+ AUTHORIZED = 'AUTHORIZED'
32
+ CAPTURING = 'CAPTURING'
33
+ COMPLETED = 'COMPLETED'
34
+ COMPENSATING = 'COMPENSATING'
35
+ VOIDED = 'VOIDED'
36
+ FAILED = 'FAILED'
37
+ RECONCILIATION_REQUIRED = 'RECONCILIATION_REQUIRED'
38
+
39
+ ALL = [COMPOSING, AUTHORIZING, AWAITING_3DS, AWAITING_ACTION, AWAITING_CREDIT_APPROVAL, AWAITING_REPLACEMENT_CARD,
40
+ AUTHORIZED, CAPTURING, COMPLETED, COMPENSATING, VOIDED, FAILED, RECONCILIATION_REQUIRED].freeze
41
+ end
42
+
43
+ # Webhook events of a split payment. The result of the main payment arrives as payment.captured /
44
+ # payment.failed with settlementMode SPLIT; deliver the order on that event.
45
+ module SplitPaymentEvents
46
+ COMPLETED = 'payment.split.completed'
47
+ VOIDED = 'payment.split.voided'
48
+ COMPENSATING = 'payment.split.compensating'
49
+ # The non-reversible leg's result is being confirmed; card holds are kept until then.
50
+ OUTCOME_PENDING = 'payment.split.outcome_pending'
51
+ # The order could not be fully collected.
52
+ RECONCILIATION_REQUIRED = 'payment.split.reconciliation_required'
53
+ # Leg event: a charged leg is being refunded and retried until it succeeds.
54
+ LEG_REFUND_PENDING = 'payment.split.leg_refund_pending'
55
+
56
+ ALL = [COMPLETED, VOIDED, COMPENSATING, OUTCOME_PENDING, RECONCILIATION_REQUIRED, LEG_REFUND_PENDING].freeze
57
+ end
58
+
59
+ # Leg and list rules of the split payment endpoints.
60
+ module SplitPaymentRules
61
+ LIST_MAX_LIMIT = 100
62
+ LIST_MAX_VALUES = 20
63
+ FILTER_TEXT_MAX_LENGTH = 200
64
+ AFTER_MAX_LENGTH = 2048
65
+ ISO_8601 = /\A\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:?\d{2})?)?\z/
66
+
67
+ module_function
68
+
69
+ # A card leg (paymentMethod omitted, empty or CARD) carries no method block; a non-card leg carries
70
+ # only its own block, which must be one of SPLIT_LEG_BLOCK_FIELDS.
71
+ def leg!(leg, path)
72
+ excluded = (METHOD_BLOCK_FIELDS - SPLIT_LEG_BLOCK_FIELDS).find { |field| !leg[field].nil? }
73
+ raise ConfigurationError, "#{path}: the '#{excluded}' block cannot be sent in a split payment leg" if excluded
74
+
75
+ method = leg['paymentMethod']
76
+ if [nil, '', PaymentMethod::CARD].include?(method)
77
+ block = SPLIT_LEG_BLOCK_FIELDS.find { |field| !leg[field].nil? }
78
+ raise ConfigurationError, "#{path} is a card leg and cannot carry the '#{block}' block" if block
79
+
80
+ return
81
+ end
82
+ method_leg!(leg, path, MethodFields.normalize_payment_method(method))
83
+ end
84
+
85
+ # Query of GET /payments/split; status and currency may be a value or a list (repeated parameters).
86
+ def list_query!(filters)
87
+ data = filters.transform_keys(&:to_s)
88
+ unknown = data.keys - LIST_SPLIT_PAYMENTS_FILTERS
89
+ raise ConfigurationError, "list_splits does not take #{unknown.join(', ')}; filters: #{LIST_SPLIT_PAYMENTS_FILTERS.join(', ')}" unless unknown.empty?
90
+
91
+ LIST_SPLIT_PAYMENTS_FILTERS.each_with_object({}) do |key, query|
92
+ value = data[key]
93
+ next if value.nil? || value == ''
94
+
95
+ query[key] = filter_value!(key, value)
96
+ end
97
+ end
98
+
99
+ def method_leg!(leg, path, method)
100
+ block_name = MethodFields.block_name_of(method)
101
+ unless SPLIT_LEG_BLOCK_FIELDS.include?(block_name)
102
+ raise ConfigurationError, "#{path}: paymentMethod #{method} cannot be a split leg; a non-card leg carries one of #{SPLIT_LEG_BLOCK_FIELDS.join(', ')}"
103
+ end
104
+
105
+ other = SPLIT_LEG_BLOCK_FIELDS.find { |field| field != block_name && !leg[field].nil? }
106
+ raise ConfigurationError, "#{path}: paymentMethod #{method} takes only the '#{block_name}' block" if other
107
+
108
+ block = leg[block_name]
109
+ raise ConfigurationError, "#{path}: paymentMethod #{method} requires the '#{block_name}' block" unless block.is_a?(Hash)
110
+
111
+ fields = block.except('providerCode')
112
+ MethodFields.provider_code!(block['providerCode']) unless block['providerCode'].nil?
113
+ MethodFields.method_fields!(fields, "#{path}.#{block_name}")
114
+ return unless method == PaymentMethod::PROMISSORY_NOTE
115
+ raise ConfigurationError, "#{path}.#{block_name}.schedule cannot be sent in a split leg; use noteCount" unless fields['schedule'].nil?
116
+
117
+ PromissoryNotePlan.note_count!(fields['noteCount'], "#{path}.#{block_name}.noteCount")
118
+ end
119
+
120
+ def filter_value!(key, value)
121
+ case key
122
+ when 'status' then values!(key, value) { |entry| SplitPaymentStatus::ALL.include?(entry) }
123
+ when 'currency' then values!(key, value) { |entry| entry.is_a?(String) && entry.match?(/\A[A-Z]{3}\z/) }
124
+ when 'createdFrom', 'createdTo'
125
+ raise ConfigurationError, "#{key} must be an ISO 8601 date-time" unless value.is_a?(String) && value.match?(ISO_8601)
126
+
127
+ value
128
+ when 'limit'
129
+ raise ConfigurationError, "limit must be an integer from 1 to #{LIST_MAX_LIMIT}" unless value.is_a?(Integer) && value.between?(1, LIST_MAX_LIMIT)
130
+
131
+ value.to_s
132
+ else
133
+ max = key == 'after' ? AFTER_MAX_LENGTH : FILTER_TEXT_MAX_LENGTH
134
+ return value if value.is_a?(String) && !value.strip.empty? && value.length <= max
135
+
136
+ raise ConfigurationError, "#{key} must be a nonempty string of at most #{max} characters"
137
+ end
138
+ end
139
+
140
+ def values!(key, value, &)
141
+ values = Array(value)
142
+ raise ConfigurationError, "#{key} takes 1 to #{LIST_MAX_VALUES} values" if values.empty? || values.size > LIST_MAX_VALUES
143
+ raise ConfigurationError, "#{key} contains an invalid value" unless values.all?(&)
144
+
145
+ values
146
+ end
147
+
148
+ private_class_method :method_leg!, :filter_value!, :values!
149
+ end
150
+ end