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.
@@ -0,0 +1,215 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'digest'
4
+ require 'securerandom'
5
+
6
+ module Lunixi
7
+ # Bulk screening (/api/v1/sanction/batches) of Lunixi::Sanction: screen a whole customer file or many
8
+ # API rows as one job and download signed reports. Writes need sanction:batch_screen and actor_id, sent
9
+ # as X-Actor-Id (the person in your organization acting; required with an API key); reads need
10
+ # sanction:batch_view. Requests are checked against SANCTION_ROUTES like the screening calls.
11
+ module SanctionBatch # rubocop:disable Metrics/ModuleLength -- one method per catalog operation
12
+ BATCH_KEY = /\A[\x21-\x7e]{8,160}\z/
13
+ BATCH_FILE_TYPES = {
14
+ '.csv' => 'text/csv',
15
+ '.xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
16
+ }.freeze
17
+
18
+ # The lists a bulk screening job can cover: { lists }.
19
+ def list_catalog(risk_domain: nil)
20
+ RouteResponse.unwrap(invoke('listCatalog', query: RouteRequest.compact('riskDomain' => risk_domain)))
21
+ end
22
+
23
+ # Opens a job (DRAFT): { name, retentionDays?, defaultSubjectType?, listScope?, headlineGroups? }.
24
+ # idempotency_key (8–160 printable characters) makes a retry return the same job; without one a random
25
+ # key is sent, so the SDK's own retries cannot open a second job. Returns { batch }.
26
+ def create_batch(request, actor_id:, idempotency_key: nil)
27
+ key = idempotency_key.nil? ? "sanction-batch-#{SecureRandom.uuid}" : idempotency_key
28
+ RouteResponse.unwrap(invoke('createBatch', body: request, actor_id: actor_id, idempotency_key: key))
29
+ end
30
+
31
+ # Adds API rows to a DRAFT job (chunk_no 0–99, at most 5000 rows): { accepted, rowCount }.
32
+ def append_batch_rows(batch_id, chunk_no:, rows:, actor_id:)
33
+ batch_write('appendBatchRows', batch_id, { 'chunkNo' => chunk_no, 'rows' => rows }, actor_id)
34
+ end
35
+
36
+ # File upload, step 1: { uploadId, partSize, expiresAt, parts }. upload_batch_file runs the whole upload.
37
+ def create_batch_upload_session(batch_id, file_name:, content_type:, bytes:, sha256:, actor_id:)
38
+ body = { 'fileName' => file_name, 'contentType' => content_type, 'bytes' => bytes, 'sha256' => sha256 }
39
+ batch_write('createBatchUploadSession', batch_id, body, actor_id)
40
+ end
41
+
42
+ # File upload, last step (parts: [{ partNo, etag }]): { batch, columns, suggestedMapping, ... }.
43
+ def complete_batch_upload(batch_id, upload_id:, parts:, actor_id:)
44
+ batch_write('completeBatchUpload', batch_id, { 'uploadId' => upload_id, 'parts' => parts }, actor_id)
45
+ end
46
+
47
+ # Uploads a .csv or .xlsx file in one call: its sha256, the upload session, a PUT of every part to its
48
+ # signed URL and the completion. The PUTs go straight to the storage host with only the body and its
49
+ # Content-Length, never the access token. A failed PUT is not retried and the upload is not completed;
50
+ # call upload_batch_file again (a new session replaces the open one).
51
+ def upload_batch_file(batch_id, path, actor_id:, file_name: nil, content_type: nil)
52
+ actor = actor!(actor_id)
53
+ name = (file_name || File.basename(path.to_s)).strip
54
+ type = BATCH_FILE_TYPES[File.extname(name).downcase]
55
+ raise ConfigurationError, "file_name must end in .csv or .xlsx; got #{name.inspect}." if type.nil?
56
+ raise ConfigurationError, 'The batch file cannot be read.' unless File.file?(path) && File.readable?(path)
57
+
58
+ size = File.size(path)
59
+ raise ConfigurationError, 'The batch file is empty.' if size.zero?
60
+
61
+ session = create_batch_upload_session(batch_id, file_name: name, content_type: content_type || type, bytes: size,
62
+ sha256: Digest::SHA256.file(path).hexdigest, actor_id: actor)
63
+ parts = upload_parts!(session, size)
64
+ uploaded = File.open(path, 'rb') do |file|
65
+ parts.map do |part|
66
+ data = file.read(part['bytes'])
67
+ raise ConfigurationError, 'The batch file became shorter while it was being uploaded.' unless data&.bytesize == part['bytes']
68
+
69
+ { 'partNo' => part['partNo'], 'etag' => put_part(part, data) }
70
+ end
71
+ end
72
+ complete_batch_upload(batch_id, upload_id: session['uploadId'], parts: uploaded, actor_id: actor)
73
+ end
74
+
75
+ # Confirms which file column is which field: { batch } (VALIDATING).
76
+ def set_batch_column_mapping(batch_id, mapping:, actor_id:, default_subject_type: nil)
77
+ raise ConfigurationError, 'mapping must be a Hash of column header to field.' unless mapping.is_a?(Hash)
78
+
79
+ body = RouteRequest.compact('mapping' => mapping, 'defaultSubjectType' => default_subject_type)
80
+ batch_write('setBatchColumnMapping', batch_id, body, actor_id)
81
+ end
82
+
83
+ # Validation summary: { status, counts, invalidByReason, samples }.
84
+ def get_batch_validation(batch_id)
85
+ batch_read('getBatchValidation', batch_id)
86
+ end
87
+
88
+ # What the job will cost: { estimateRows, estimateAmountMinor, unitFeeMinor, currency, pricingSource }.
89
+ def get_batch_estimate(batch_id)
90
+ batch_read('getBatchEstimate', batch_id)
91
+ end
92
+
93
+ # Queues the job, confirming the shown estimate (409 sanction.batch.estimate_mismatch when it changed).
94
+ def submit_batch(batch_id, estimate_amount_minor:, actor_id:)
95
+ unless estimate_amount_minor.is_a?(String) && estimate_amount_minor.match?(/\A(0|[1-9][0-9]*)\z/)
96
+ raise ConfigurationError, "estimate_amount_minor must be the estimate's integer string in minor units."
97
+ end
98
+
99
+ batch_write('submitBatch', batch_id, { 'confirmEstimate' => true, 'estimateAmountMinor' => estimate_amount_minor }, actor_id)
100
+ end
101
+
102
+ # Cancels the job; rows screened before stay billed: { batch, note }.
103
+ def cancel_batch(batch_id, actor_id:, reason: nil)
104
+ batch_write('cancelBatch', batch_id, RouteRequest.compact('reason' => reason), actor_id)
105
+ end
106
+
107
+ # Your jobs, newest first. Filters: limit, cursor, status (one or a list).
108
+ def list_batches(**filters)
109
+ page('listBatches', csv(filters, 'status'))
110
+ end
111
+
112
+ def iterate_batches(**filters, &block)
113
+ RouteResponse.each_item(filters, block) { |query| list_batches(**query) }
114
+ end
115
+
116
+ # One job: { batch }.
117
+ def get_batch(batch_id)
118
+ batch_read('getBatch', batch_id)
119
+ end
120
+
121
+ # Result rows without hits. Filters: limit, cursor, decision, tier, group, listId, basis,
122
+ # customerReference, status (decision and status: one or a list).
123
+ def list_batch_results(batch_id, **filters)
124
+ RouteResponse.page(invoke('listBatchResults', params: { 'batchId' => batch_id }, query: csv(filters, 'decision', 'status')))
125
+ end
126
+
127
+ def iterate_batch_results(batch_id, **filters, &block)
128
+ RouteResponse.each_item(filters, block) { |query| list_batch_results(batch_id, **query) }
129
+ end
130
+
131
+ # One result row with its hits: { row }. row_no starts at 1. A row may carry jurisdictionRisk: its countries on
132
+ # the country risk lists, each { field, country, listCode, listName, effect, listDate } (absent on older rows;
133
+ # field may be empty).
134
+ def get_batch_result_row(batch_id, row_no)
135
+ raise ConfigurationError, 'row_no must be a positive integer.' unless row_no.is_a?(Integer) && row_no.positive?
136
+
137
+ RouteResponse.unwrap(invoke('getBatchResultRow', params: { 'batchId' => batch_id, 'rowNo' => row_no.to_s }))
138
+ end
139
+
140
+ # A signed report URL (300 s): { url, expiresAt, sha256, bytes, fileName }. lang (tr, en) picks the pdf language.
141
+ def get_batch_report_url(batch_id, format, lang: nil)
142
+ raise ConfigurationError, "format must be one of #{SanctionBatchReportFormat::ALL.join(', ')}." unless SanctionBatchReportFormat::ALL.include?(format)
143
+ raise ConfigurationError, 'lang must be tr or en.' unless lang.nil? || %w[tr en].include?(lang)
144
+
145
+ params = { 'batchId' => batch_id, 'format' => format }
146
+ RouteResponse.unwrap(invoke('getBatchReportUrl', params: params, query: RouteRequest.compact('lang' => lang)))
147
+ end
148
+
149
+ # Erases the job's rows, results and reports now: { certificate }.
150
+ def erase_batch(batch_id, actor_id:, reason: nil)
151
+ batch_write('eraseBatch', batch_id, RouteRequest.compact('reason' => reason), actor_id)
152
+ end
153
+
154
+ # The erasure certificate of an erased job: { certificate }.
155
+ def get_batch_erasure_certificate(batch_id)
156
+ batch_read('getBatchErasureCertificate', batch_id)
157
+ end
158
+
159
+ private
160
+
161
+ def batch_write(name, batch_id, body, actor_id)
162
+ RouteResponse.unwrap(invoke(name, params: { 'batchId' => batch_id }, body: body, actor_id: actor_id))
163
+ end
164
+
165
+ def batch_read(name, batch_id)
166
+ RouteResponse.unwrap(invoke(name, params: { 'batchId' => batch_id }))
167
+ end
168
+
169
+ def batch_key!(key)
170
+ return key if key.is_a?(String) && key.match?(BATCH_KEY)
171
+
172
+ raise ConfigurationError, 'idempotency_key must be 8-160 printable ASCII characters without spaces.'
173
+ end
174
+
175
+ # One value or a list, sent comma-separated (the gateway splits it).
176
+ def csv(filters, *keys)
177
+ keys.each_with_object(filters.dup) do |key, out|
178
+ found = out.keys.find { |name| name.to_s == key }
179
+ next if found.nil? || !out[found].is_a?(Array)
180
+
181
+ joined = out[found].map { |value| value.to_s.strip }.reject(&:empty?).join(',')
182
+ out[found] = joined.empty? ? '' : joined
183
+ end
184
+ end
185
+
186
+ # The session's parts, used only if they are 1..n with http(s) URLs adding up to the file.
187
+ def upload_parts!(session, size) # rubocop:disable Metrics/CyclomaticComplexity,Metrics/PerceivedComplexity -- multipart upload state machine
188
+ parts = session.is_a?(Hash) ? session['parts'] : nil
189
+ usable = session.is_a?(Hash) && session['uploadId'].is_a?(String) && !session['uploadId'].empty? && parts.is_a?(Array) && !parts.empty?
190
+ usable &&= parts.each_with_index.all? do |part, index|
191
+ part.is_a?(Hash) && part['partNo'] == index + 1 && part['url'].is_a?(String) && part['url'].match?(%r{\Ahttps?://}i) &&
192
+ part['bytes'].is_a?(Integer) && part['bytes'].positive?
193
+ end
194
+ return parts if usable && parts.sum { |part| part['bytes'] } == size
195
+
196
+ raise ApiError.new(status: 0, message: 'The batch upload session did not return usable upload parts.')
197
+ end
198
+
199
+ # The PUT of one part to its signed URL. It deliberately does not use Client#request: the access token
200
+ # must never reach the storage host. Only the body and its Content-Length are sent; returns the ETag.
201
+ def put_part(part, data)
202
+ raise ConfigurationError, 'The batch file upload needs a storage transport.' if @storage_transport.nil?
203
+
204
+ response = @storage_transport.call(method: 'PUT', uri: URI.parse(part['url']), headers: { 'Content-Length' => data.bytesize.to_s }.freeze, body: data)
205
+ raise TransportError, 'Batch file upload to storage returned an invalid response' unless response.is_a?(Response) && response.status.is_a?(Integer)
206
+ raise ApiError.new(status: response.status, code: PaymentLinkImageRules.storage_error_code(response.body)) unless response.status.between?(200, 299)
207
+
208
+ etag = response.headers.is_a?(Hash) ? response.headers.find { |name, _| name.to_s.casecmp?('etag') }&.last : nil
209
+ etag = etag.first if etag.is_a?(Array)
210
+ raise ApiError.new(status: response.status, code: 'STORAGE_ETAG_MISSING') if etag.nil? || etag.to_s.empty?
211
+
212
+ etag.to_s
213
+ end
214
+ end
215
+ end
@@ -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