lunixi-sdk 1.2.2 → 1.3.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.
Files changed (69) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -0
  3. data/README.md +262 -9
  4. data/README.tr.md +266 -7
  5. data/lib/lunixi/bank_connect.rb +340 -0
  6. data/lib/lunixi/bank_connect_filters.rb +114 -0
  7. data/lib/lunixi/bank_connect_values.rb +205 -0
  8. data/lib/lunixi/bank_transfer.rb +106 -0
  9. data/lib/lunixi/card_requests.rb +150 -0
  10. data/lib/lunixi/client.rb +57 -16
  11. data/lib/lunixi/direct_method_payment_request.rb +243 -0
  12. data/lib/lunixi/enabled_installments.rb +28 -0
  13. data/lib/lunixi/errors.rb +69 -3
  14. data/lib/lunixi/fraud.rb +81 -5
  15. data/lib/lunixi/identity.rb +94 -0
  16. data/lib/lunixi/identity_values.rb +28 -0
  17. data/lib/lunixi/insurance.rb +294 -0
  18. data/lib/lunixi/insurance_request.rb +134 -0
  19. data/lib/lunixi/insurance_values.rb +200 -0
  20. data/lib/lunixi/kyc.rb +189 -0
  21. data/lib/lunixi/kyc_values.rb +158 -0
  22. data/lib/lunixi/marketplace.rb +264 -0
  23. data/lib/lunixi/marketplace_values.rb +86 -0
  24. data/lib/lunixi/method_fields.rb +142 -0
  25. data/lib/lunixi/money.rb +7 -4
  26. data/lib/lunixi/payment_link_filters.rb +32 -0
  27. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  28. data/lib/lunixi/payment_link_rules.rb +132 -0
  29. data/lib/lunixi/payment_link_values.rb +134 -0
  30. data/lib/lunixi/payment_links.rb +152 -0
  31. data/lib/lunixi/payment_values.rb +86 -0
  32. data/lib/lunixi/payments.rb +154 -5
  33. data/lib/lunixi/physical_pos.rb +183 -0
  34. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  35. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  36. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  37. data/lib/lunixi/physical_pos_filters.rb +58 -0
  38. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  39. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  40. data/lib/lunixi/physical_pos_management.rb +326 -0
  41. data/lib/lunixi/physical_pos_money.rb +46 -0
  42. data/lib/lunixi/physical_pos_request.rb +126 -0
  43. data/lib/lunixi/physical_pos_responses.rb +102 -0
  44. data/lib/lunixi/physical_pos_results.rb +52 -0
  45. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  46. data/lib/lunixi/physical_pos_value.rb +43 -0
  47. data/lib/lunixi/physical_pos_values.rb +203 -0
  48. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  49. data/lib/lunixi/product_webhooks.rb +106 -0
  50. data/lib/lunixi/promissory_note.rb +155 -0
  51. data/lib/lunixi/reference.rb +41 -0
  52. data/lib/lunixi/route_request.rb +121 -0
  53. data/lib/lunixi/route_response.rb +101 -0
  54. data/lib/lunixi/route_table.rb +128 -0
  55. data/lib/lunixi/route_value.rb +60 -0
  56. data/lib/lunixi/sanction.rb +244 -0
  57. data/lib/lunixi/sanction_values.rb +132 -0
  58. data/lib/lunixi/split_payment.rb +145 -0
  59. data/lib/lunixi/subscription_resources.rb +355 -0
  60. data/lib/lunixi/subscription_values.rb +220 -0
  61. data/lib/lunixi/subscriptions.rb +202 -0
  62. data/lib/lunixi/version.rb +1 -1
  63. data/lib/lunixi/wallet.rb +153 -0
  64. data/lib/lunixi/wallet_resources.rb +402 -0
  65. data/lib/lunixi/wallet_routes.rb +123 -0
  66. data/lib/lunixi/wallet_values.rb +71 -0
  67. data/lib/lunixi/wire_money.rb +67 -0
  68. data/lib/lunixi.rb +57 -0
  69. metadata +58 -1
@@ -0,0 +1,134 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # The CSV of insurance.export_reconciliation. data: the file bytes (UTF-8 with BOM, one line per
5
+ # policy, amounts in minor units). truncated: the file holds INSURANCE_EXPORT_ORDER_CAP orders and
6
+ # next_cursor continues it (pass it as cursor:). aborted: the file ends with the gateway's abort line;
7
+ # it is incomplete, request it again.
8
+ InsuranceReconciliationExport = Struct.new(:data, :truncated, :next_cursor, :aborted, keyword_init: true) do
9
+ def truncated?
10
+ truncated == true
11
+ end
12
+
13
+ def aborted?
14
+ aborted == true
15
+ end
16
+
17
+ def inspect
18
+ "#<Lunixi::InsuranceReconciliationExport bytes=#{data.bytesize} truncated=#{truncated} aborted=#{aborted}>"
19
+ end
20
+ end
21
+
22
+ # Local checks of the insurance requests and filters. Type objects (insured, tickets ...) are sent as
23
+ # given: their field rules are the gateway's. Not a public API.
24
+ module InsuranceRequest
25
+ UUID = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i
26
+ CURSOR_MAX_LENGTH = 512
27
+ TEXT_MAX_LENGTH = 128
28
+ CODE_MAX_LENGTH = 64
29
+ TRUNCATED_LINE = /\A# truncated=true orderCap=(\d+) nextCursor=(\S+)\s*\z/
30
+ ABORTED_LINE = /\A# export-aborted=true\s*\z/
31
+
32
+ module_function
33
+
34
+ # The query of a read route (INSURANCE_FILTERS); nil and '' are left out.
35
+ def query!(filters, route, required = [])
36
+ given = RouteRequest.wire_keys!(filters || {}, INSURANCE_FILTERS.fetch(route), 'insurance', 'filter')
37
+ query = given.each_with_object({}) do |(key, value), out|
38
+ out[key] = filter_value(key, value) unless value == ''
39
+ end
40
+ missing = required.reject { |key| query.key?(key) }
41
+ raise ConfigurationError, "#{route} requires #{missing.map { |key| "'#{key}'" }.join(' and ')}." unless missing.empty?
42
+
43
+ query
44
+ end
45
+
46
+ def filter_value(key, value)
47
+ case key
48
+ when 'limit'
49
+ unless value.is_a?(Integer) && value.between?(1, INSURANCE_MAX_LIMIT)
50
+ raise ConfigurationError, "'limit' must be an integer from 1 to #{INSURANCE_MAX_LIMIT}."
51
+ end
52
+
53
+ value
54
+ when 'cursor'
55
+ unless value.is_a?(String) && value.length <= CURSOR_MAX_LENGTH
56
+ raise ConfigurationError, "'cursor' must be the next_cursor of the previous page, passed back unchanged."
57
+ end
58
+
59
+ value
60
+ when 'currency' then RouteValue.currency!(value, key)
61
+ when 'paymentIntentId', 'connectionId' then uuid!(value, key)
62
+ when 'from', 'to' then RouteValue.iso_time!(value, key)
63
+ when 'merchantOrderId' then RouteValue.text!(value, key, TEXT_MAX_LENGTH)
64
+ when 'status' then lead_status!(value)
65
+ else RouteValue.text!(value, key, CODE_MAX_LENGTH)
66
+ end
67
+ end
68
+
69
+ def lead_status!(value)
70
+ return value if InsuranceLeadStatus::ALL.include?(value)
71
+
72
+ raise ConfigurationError, "'status' must be one of #{InsuranceLeadStatus::ALL.join(', ')}."
73
+ end
74
+
75
+ def uuid!(value, field)
76
+ id = value.is_a?(String) ? value.strip : ''
77
+ raise ConfigurationError, "'#{field}' must be a Lunixi id (UUID)." unless id.match?(UUID)
78
+
79
+ id
80
+ end
81
+
82
+ def reference_kind!(kind)
83
+ return kind if InsuranceReferenceKind::ALL.include?(kind)
84
+
85
+ raise ConfigurationError, "Reference kind must be one of #{InsuranceReferenceKind::ALL.join(', ')}."
86
+ end
87
+
88
+ # context: { items } — the basket items the payment carries (1–100 Hashes, sent as given).
89
+ def context!(value)
90
+ context = RouteRequest.wire_keys!(value, %w[items], 'context')
91
+ items = context['items']
92
+ unless items.is_a?(Array) && items.length.between?(1, INSURANCE_MAX_CONTEXT_ITEMS) && items.all?(Hash)
93
+ raise ConfigurationError, "'context.items' must hold 1 to #{INSURANCE_MAX_CONTEXT_ITEMS} basket items."
94
+ end
95
+
96
+ { 'items' => items }
97
+ end
98
+
99
+ def required_key!(key, operation)
100
+ if key.nil? || key == ''
101
+ raise ConfigurationError, "A stable Idempotency-Key is required for #{operation}. Reuse the same key when retrying the same operation."
102
+ end
103
+
104
+ RouteRequest.printable_idempotency_key!(key)
105
+ end
106
+
107
+ def optional_key(key)
108
+ key.nil? || key == '' ? nil : RouteRequest.printable_idempotency_key!(key)
109
+ end
110
+
111
+ def positive_minor!(value, field)
112
+ Money.minor(value, positive: true)
113
+ rescue ConfigurationError
114
+ raise ConfigurationError, "'#{field}' must be a positive canonical minor-unit string such as \"4990\" (not a number).", cause: nil
115
+ end
116
+
117
+ # The lead note is free text sent as given (not trimmed), at most 1000 characters.
118
+ def lead_note!(value)
119
+ raise ConfigurationError, "'note' must be a string." unless value.is_a?(String)
120
+ raise ConfigurationError, "'note' must be at most #{INSURANCE_LEAD_NOTE_MAX_LENGTH} characters." if value.length > INSURANCE_LEAD_NOTE_MAX_LENGTH
121
+
122
+ value
123
+ end
124
+
125
+ def export(bytes)
126
+ text = bytes.dup.force_encoding(Encoding::UTF_8)
127
+ text = text.scrub('') unless text.valid_encoding?
128
+ last = text.split(/\r?\n/).reject(&:empty?).last.to_s
129
+ truncated = TRUNCATED_LINE.match(last)
130
+ InsuranceReconciliationExport.new(data: bytes, truncated: !truncated.nil?, next_cursor: truncated ? truncated[2] : nil,
131
+ aborted: last.match?(ABORTED_LINE))
132
+ end
133
+ end
134
+ end
@@ -0,0 +1,200 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Insurance values, request fields and filters (/api/v1/insurance, product INSURANCE_SERVICE).
5
+
6
+ # Who collects the premium. PROVIDER orders cannot be completed through this API yet.
7
+ module InsurancePremiumCollectedBy
8
+ MERCHANT = 'MERCHANT'
9
+ PROVIDER = 'PROVIDER'
10
+ ALL = [MERCHANT, PROVIDER].freeze
11
+ end
12
+
13
+ # Status of a quote option. Only a QUOTED option that has not expired becomes an order.
14
+ module InsuranceQuoteStatus
15
+ REQUESTED = 'REQUESTED'
16
+ QUOTED = 'QUOTED'
17
+ EXPIRED = 'EXPIRED'
18
+ REJECTED = 'REJECTED'
19
+ ERROR = 'ERROR'
20
+ ALL = [REQUESTED, QUOTED, EXPIRED, REJECTED, ERROR].freeze
21
+ end
22
+
23
+ # The order's overall status, derived on every read from the four axes in this order: REFUNDED,
24
+ # CANCELLED, FAILED, ACTION_REQUIRED, PROCESSING, PARTIALLY_ACTIVE, ACTIVE, CREATED.
25
+ module InsuranceOrderStatus
26
+ CREATED = 'CREATED'
27
+ PROCESSING = 'PROCESSING'
28
+ ACTION_REQUIRED = 'ACTION_REQUIRED'
29
+ PARTIALLY_ACTIVE = 'PARTIALLY_ACTIVE'
30
+ ACTIVE = 'ACTIVE'
31
+ FAILED = 'FAILED'
32
+ CANCELLED = 'CANCELLED'
33
+ REFUNDED = 'REFUNDED'
34
+ ALL = [CREATED, PROCESSING, ACTION_REQUIRED, PARTIALLY_ACTIVE, ACTIVE, FAILED, CANCELLED, REFUNDED].freeze
35
+ end
36
+
37
+ module InsuranceCollectionStatus
38
+ NOT_STARTED = 'NOT_STARTED'
39
+ PENDING = 'PENDING'
40
+ ACTION_REQUIRED = 'ACTION_REQUIRED'
41
+ COLLECTED = 'COLLECTED'
42
+ FAILED = 'FAILED'
43
+ UNKNOWN = 'UNKNOWN'
44
+ ALL = [NOT_STARTED, PENDING, ACTION_REQUIRED, COLLECTED, FAILED, UNKNOWN].freeze
45
+ end
46
+
47
+ module InsurancePolicyStatus
48
+ NOT_REQUESTED = 'NOT_REQUESTED'
49
+ PENDING = 'PENDING'
50
+ PARTIALLY_ISSUED = 'PARTIALLY_ISSUED'
51
+ ISSUED = 'ISSUED'
52
+ FAILED_RETRYABLE = 'FAILED_RETRYABLE'
53
+ FAILED_FINAL = 'FAILED_FINAL'
54
+ UNKNOWN = 'UNKNOWN'
55
+ CANCEL_PENDING = 'CANCEL_PENDING'
56
+ CANCELLED = 'CANCELLED'
57
+ ALL = [NOT_REQUESTED, PENDING, PARTIALLY_ISSUED, ISSUED, FAILED_RETRYABLE, FAILED_FINAL, UNKNOWN, CANCEL_PENDING, CANCELLED].freeze
58
+ end
59
+
60
+ module InsuranceRefundStatus
61
+ NONE = 'NONE'
62
+ REQUIRED = 'REQUIRED'
63
+ PENDING = 'PENDING'
64
+ REFUNDED = 'REFUNDED'
65
+ FAILED = 'FAILED'
66
+ ALL = [NONE, REQUIRED, PENDING, REFUNDED, FAILED].freeze
67
+ end
68
+
69
+ # The policy document axis; it does not change the overall status.
70
+ module InsuranceDocumentStatus
71
+ NOT_AVAILABLE = 'NOT_AVAILABLE'
72
+ PENDING = 'PENDING'
73
+ AVAILABLE = 'AVAILABLE'
74
+ FAILED = 'FAILED'
75
+ ALL = [NOT_AVAILABLE, PENDING, AVAILABLE, FAILED].freeze
76
+ end
77
+
78
+ module InsurancePaymentMode
79
+ LUNIXI_PAYMENT = 'LUNIXI_PAYMENT'
80
+ EXTERNAL_PAYMENT = 'EXTERNAL_PAYMENT'
81
+ NO_PAYMENT = 'NO_PAYMENT'
82
+ ALL = [LUNIXI_PAYMENT, EXTERNAL_PAYMENT, NO_PAYMENT].freeze
83
+ end
84
+
85
+ module InsuranceOrderSurface
86
+ MERCHANT_API = 'MERCHANT_API'
87
+ CHECKOUT_FORM = 'CHECKOUT_FORM'
88
+ PANEL = 'PANEL'
89
+ ALL = [MERCHANT_API, CHECKOUT_FORM, PANEL].freeze
90
+ end
91
+
92
+ # Status of a lead. PENDING: the provider call is running. SUBMITTED: the provider received it
93
+ # (insurance.lead.submitted). UNKNOWN: the outcome is not known; it is never sent again (open a new
94
+ # lead with a new Idempotency-Key if needed). FAILED: refused or never reached the provider (errorCode).
95
+ module InsuranceLeadStatus
96
+ PENDING = 'PENDING'
97
+ SUBMITTED = 'SUBMITTED'
98
+ UNKNOWN = 'UNKNOWN'
99
+ FAILED = 'FAILED'
100
+ ALL = [PENDING, SUBMITTED, UNKNOWN, FAILED].freeze
101
+ end
102
+
103
+ # Reference code lists (insurance.list_reference_values(kind)). DISTRICT, DEVICE_MODEL, VEHICLE_MODEL,
104
+ # BANK_BRANCH and PET_BREED need parentCode (province, brand, bank, CAT | DOG).
105
+ module InsuranceReferenceKind
106
+ COUNTRY = 'COUNTRY'
107
+ CITY = 'CITY'
108
+ DISTRICT = 'DISTRICT'
109
+ DEVICE_BRAND = 'DEVICE_BRAND'
110
+ DEVICE_MODEL = 'DEVICE_MODEL'
111
+ VEHICLE_BRAND = 'VEHICLE_BRAND'
112
+ VEHICLE_MODEL = 'VEHICLE_MODEL'
113
+ VEHICLE_TYPE = 'VEHICLE_TYPE'
114
+ PRODUCT_CATEGORY = 'PRODUCT_CATEGORY'
115
+ VEHICLE_USAGE = 'VEHICLE_USAGE'
116
+ LIABILITY_LIMIT = 'LIABILITY_LIMIT'
117
+ OCCUPATION = 'OCCUPATION'
118
+ PET_BREED = 'PET_BREED'
119
+ DWELLING_TYPE = 'DWELLING_TYPE'
120
+ DWELLING_FLOOR = 'DWELLING_FLOOR'
121
+ BANK = 'BANK'
122
+ BANK_BRANCH = 'BANK_BRANCH'
123
+ FINANCE_INSTITUTION = 'FINANCE_INSTITUTION'
124
+ MEDICAL_PROCEDURE_COVER = 'MEDICAL_PROCEDURE_COVER'
125
+ ALL = [COUNTRY, CITY, DISTRICT, DEVICE_BRAND, DEVICE_MODEL, VEHICLE_BRAND, VEHICLE_MODEL, VEHICLE_TYPE, PRODUCT_CATEGORY,
126
+ VEHICLE_USAGE, LIABILITY_LIMIT, OCCUPATION, PET_BREED, DWELLING_TYPE, DWELLING_FLOOR, BANK, BANK_BRANCH,
127
+ FINANCE_INSTITUTION, MEDICAL_PROCEDURE_COVER].freeze
128
+ end
129
+
130
+ # Insurance webhook events (subscription insurance.*). Read them with Lunixi::InsuranceWebhook.parse;
131
+ # deduplicate on the event id (data.eventId is the same value).
132
+ module InsuranceEvents
133
+ # The order's policies were issued.
134
+ POLICY_ISSUED = 'insurance.policy.issued'
135
+ # The policy could not be issued or the premium was not collected; data.errorCode says why.
136
+ POLICY_FAILED = 'insurance.policy.failed'
137
+ # The collected premium has to be refunded; data.errorCode says why.
138
+ REFUND_REQUIRED = 'insurance.refund.required'
139
+ # A policy document can be downloaded (policies[].documentUrl).
140
+ POLICY_DOCUMENT_READY = 'insurance.policy.document_ready'
141
+ # The provider confirmed the cancellation.
142
+ POLICY_CANCELLED = 'insurance.policy.cancelled'
143
+ # The premium refund completed.
144
+ REFUND_COMPLETED = 'insurance.refund.completed'
145
+ # The insurance provider received a lead; data is a lead summary, not an order.
146
+ LEAD_SUBMITTED = 'insurance.lead.submitted'
147
+ PATTERN = 'insurance.*'
148
+ ORDER_EVENTS = [POLICY_ISSUED, POLICY_FAILED, REFUND_REQUIRED, POLICY_DOCUMENT_READY, POLICY_CANCELLED, REFUND_COMPLETED].freeze
149
+ LEAD_EVENTS = [LEAD_SUBMITTED].freeze
150
+ ALL = (ORDER_EVENTS + LEAD_EVENTS).freeze
151
+ end
152
+
153
+ # The type objects of the gateway's type body, one per insurance type (a product's typeObject).
154
+ INSURANCE_TYPE_OBJECT_FIELDS = %w[tickets stay device product vehicle trip rental instrument event accident procedure pet residence abroadStay].freeze
155
+ # Top-level fields of create_quote. The type objects are sent as given: their field rules are the
156
+ # gateway's (422 insurance.validation.invalid with every details.errors[{ field, reason }]).
157
+ INSURANCE_QUOTE_FIELDS = (%w[insuranceType schemaVersion currency paymentIntentId context merchantOrderId policyholder insured] +
158
+ INSURANCE_TYPE_OBJECT_FIELDS).freeze
159
+ # Top-level fields of create_lead: the type body without basket, currency and order fields, plus
160
+ # shipment, company and the free note.
161
+ INSURANCE_LEAD_FIELDS = (%w[insuranceType schemaVersion policyholder insured] + INSURANCE_TYPE_OBJECT_FIELDS + %w[shipment company note]).freeze
162
+ INSURANCE_PRODUCT_SEARCH_FIELDS = %w[currency insuranceType context].freeze
163
+ INSURANCE_ORDER_FIELDS = %w[quoteId merchantOrderId consent].freeze
164
+ INSURANCE_CONSENT_FIELDS = %w[termsVersion termsSha256 acceptedAt].freeze
165
+ # Fields of confirm_payment (a premium collected outside Lunixi).
166
+ INSURANCE_EXTERNAL_PAYMENT_FIELDS = %w[externalPaymentId paidAmount paidCurrency paidAt paymentProvider].freeze
167
+ # Fields of externalRefund (refund_premium for a premium collected outside Lunixi).
168
+ INSURANCE_EXTERNAL_REFUND_FIELDS = %w[externalRefundId refundedAt].freeze
169
+
170
+ # Query filters each read accepts (the gateway rejects any other with 400).
171
+ INSURANCE_FILTERS = {
172
+ 'listProducts' => %w[currency paymentIntentId insuranceType].freeze,
173
+ 'listReferenceValues' => %w[parentCode limit cursor].freeze,
174
+ 'listOrders' => %w[limit cursor paymentIntentId merchantOrderId].freeze,
175
+ 'getReconciliationSummary' => %w[from to connectionId insuranceType currency].freeze,
176
+ 'listReconciliationOrders' => %w[from to connectionId insuranceType currency limit cursor].freeze,
177
+ 'exportReconciliation' => %w[from to connectionId insuranceType currency cursor].freeze,
178
+ 'listLeads' => %w[limit cursor insuranceType status].freeze
179
+ }.freeze
180
+
181
+ # Idempotency-Key of the insurance routes: 8–200 printable ASCII characters. Required for create_order,
182
+ # confirm_payment, issue_policy, cancel_order, refund_premium and create_lead; optional for
183
+ # create_quote and bind_payment.
184
+ INSURANCE_IDEMPOTENCY_KEY_PATTERN = RouteRequest::PRINTABLE_IDEMPOTENCY_KEY
185
+ INSURANCE_MAX_LIMIT = 100
186
+ # Most basket items one context.items may carry.
187
+ INSURANCE_MAX_CONTEXT_ITEMS = 100
188
+ # Orders in one reconciliation CSV file; a longer export ends with a continuation line.
189
+ INSURANCE_EXPORT_ORDER_CAP = 20_000
190
+ INSURANCE_LEAD_NOTE_MAX_LENGTH = 1000
191
+
192
+ # data fields of the order webhooks (InsuranceEvents::ORDER_EVENTS); errorCode only on
193
+ # insurance.policy.failed and insurance.refund.required.
194
+ INSURANCE_WEBHOOK_FIELDS = %w[
195
+ eventId eventType merchantId insuranceOrderId paymentIntentId merchantOrderId insuranceType premiumCollectedBy provider status
196
+ collectionStatus policyStatus refundStatus documentStatus premiumAmount currency policies errorCode createdAt
197
+ ].freeze
198
+ # data fields of insurance.lead.submitted (lead: { leadId, insuranceType, schemaVersion, status, submittedAt, createdAt }).
199
+ INSURANCE_LEAD_WEBHOOK_FIELDS = %w[eventId eventType merchantId lead createdAt].freeze
200
+ end
data/lib/lunixi/kyc.rb ADDED
@@ -0,0 +1,189 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # KYC / KYB / evidence sessions (/api/v1/kyc, client.kyc).
5
+ #
6
+ # Calls carry the access token only (no per-request signature). Your server creates the session
7
+ # (externalCustomerId = your own user id, echoed on every webhook); the browser SDK then runs the
8
+ # capture with the publishable key. The kyc.* webhook is the authority for the verification result.
9
+ #
10
+ # Bodies and filters are checked against KYC_ROUTES before anything is sent; an error names the field,
11
+ # never its value (a document image never appears in an error). Keys are the wire names (String or
12
+ # Symbol; snake_case works too).
13
+ #
14
+ # Session calls return the envelope's data ({ session, capturePolicy, ... }; no personal data comes
15
+ # back, only status, decision, risk and the achieved assurance). Lists return a Lunixi::ListPage.
16
+ class Kyc
17
+ SESSION_LIST_FILTERS = %w[limit cursor pageSize pageToken].freeze
18
+
19
+ # True for APPROVED, REJECTED, MANUAL_REVIEW, EXPIRED, ABANDONED and CANCELLED (case-insensitive).
20
+ def self.session_terminal?(status)
21
+ status.is_a?(String) && KycSessionStatus::TERMINAL_STATES.include?(status.upcase)
22
+ end
23
+
24
+ # Rank on the assurance ladder: HIGH 3, SUBSTANTIAL 2, LOW 1, anything else 0.
25
+ def self.assurance_rank(level)
26
+ { KycAssuranceLevel::HIGH => 3, KycAssuranceLevel::SUBSTANTIAL => 2, KycAssuranceLevel::LOW => 1 }
27
+ .fetch(level.is_a?(String) ? level.upcase : '', 0)
28
+ end
29
+
30
+ # True when achieved meets or exceeds required.
31
+ def self.assurance_meets?(achieved, required)
32
+ assurance_rank(achieved) >= assurance_rank(required)
33
+ end
34
+
35
+ def initialize(client)
36
+ @routes = RouteTable.new(client, KYC_ROUTES)
37
+ end
38
+
39
+ # { subjectId, sessionType, externalCustomerId?, customerMode?, person? | company? | customer?,
40
+ # jurisdiction?, requiredDocumentTypes?, primaryDocumentType?, evidencePurpose?, ttlMinutes?,
41
+ # metadata? }. person / company are sent as customer with customerType PERSON / COMPANY; metadata is
42
+ # sent as evidenceContextJson. An Idempotency-Key (idempotency_key: or the request's idempotencyKey)
43
+ # goes in the header and the body.
44
+ def create_session(request, idempotency_key: nil)
45
+ body, key = session_body('createSession', request, idempotency_key)
46
+ @routes.data('createSession', body: body, idempotency_key: key)
47
+ end
48
+
49
+ def get_session(session_id)
50
+ @routes.data('getSession', params: { 'sessionId' => session_id })
51
+ end
52
+
53
+ # Filters: limit, cursor (pageSize / pageToken are read as the same). Anything else is refused: the
54
+ # merchant list has no status or customer filter, and dropping one would return every session.
55
+ def list_sessions(**filters)
56
+ given = RouteRequest.wire_keys!(filters, SESSION_LIST_FILTERS, 'listSessions', 'filter')
57
+ query = RouteRequest.compact('limit' => given.fetch('limit', given['pageSize']), 'cursor' => given.fetch('cursor', given['pageToken']))
58
+ @routes.page('listSessions', query: query)
59
+ end
60
+
61
+ def iterate_sessions(**filters, &block)
62
+ RouteResponse.each_item(filters, block) { |query| list_sessions(**query) }
63
+ end
64
+
65
+ # Applicant jurisdiction (ISO country) on a server-created session.
66
+ def set_jurisdiction(session_id, jurisdiction)
67
+ @routes.data('setJurisdiction', params: { 'sessionId' => session_id },
68
+ body: { 'jurisdiction' => RouteValue.text!(jurisdiction, 'jurisdiction') })
69
+ end
70
+
71
+ # PASSPORT, NATIONAL_ID, DRIVERS_LICENSE or RESIDENCE_PERMIT.
72
+ def set_primary_document(session_id, document_type)
73
+ @routes.data('setPrimaryDocument', params: { 'sessionId' => session_id },
74
+ body: { 'documentType' => RouteValue.text!(document_type, 'documentType') })
75
+ end
76
+
77
+ # Server-side document upload (most flows use the browser SDK): { documentType, fileBase64, mimeType,
78
+ # side?, jurisdiction?, metadataJson?, idempotencyKey? }. The image never appears in an error message.
79
+ def upload_document(session_id, document)
80
+ raise ConfigurationError, 'uploadDocument document must be a Hash.' unless document.is_a?(Hash)
81
+
82
+ @routes.data('uploadDocument', params: { 'sessionId' => session_id }, body: document)
83
+ end
84
+
85
+ # The session's event timeline (audit).
86
+ def timeline(session_id)
87
+ @routes.data('timeline', params: { 'sessionId' => session_id })
88
+ end
89
+
90
+ def submit(session_id)
91
+ @routes.data('submit', params: { 'sessionId' => session_id })
92
+ end
93
+
94
+ def manual_review(session_id, reason_code: nil, reason_detail: nil)
95
+ body = RouteRequest.compact('reasonCode' => RouteValue.optional_text(reason_code, 'reasonCode'),
96
+ 'reasonDetail' => RouteValue.optional_text(reason_detail, 'reasonDetail'))
97
+ @routes.data('manualReview', params: { 'sessionId' => session_id }, body: body)
98
+ end
99
+
100
+ # An EVIDENCE session (proof-of-X), optionally linked to a payment or order; the same body as
101
+ # create_session.
102
+ def evidence_request(request, idempotency_key: nil)
103
+ body, key = session_body('evidenceRequest', request, idempotency_key)
104
+ @routes.data('evidenceRequest', body: body, idempotency_key: key)
105
+ end
106
+
107
+ # Your KYC policy (required assurance, providers ...).
108
+ def merchant_policy
109
+ @routes.data('merchantPolicy')
110
+ end
111
+
112
+ def update_merchant_policy(policy)
113
+ @routes.data('updateMerchantPolicy', body: policy)
114
+ end
115
+
116
+ # Rotates the KYC webhook signing secret.
117
+ def rotate_webhook_secret
118
+ @routes.data('rotateWebhookSecret')
119
+ end
120
+
121
+ # KYC webhook deliveries; filters limit, status.
122
+ def webhook_outbox(**filters)
123
+ @routes.page('webhookOutbox', query: filters)
124
+ end
125
+
126
+ def retry_webhook_event(event_id)
127
+ @routes.data('retryWebhookEvent', params: { 'eventId' => event_id })
128
+ end
129
+
130
+ # Data erasure requests; filters limit, status.
131
+ def erasure_requests(**filters)
132
+ @routes.page('erasureRequests', query: filters)
133
+ end
134
+
135
+ def inspect
136
+ '#<Lunixi::Kyc>'
137
+ end
138
+
139
+ private
140
+
141
+ def session_body(name, request, idempotency_key)
142
+ body = RouteRequest.wire_hash!(request, "#{name} request")
143
+ person = body.delete('person')
144
+ company = body.delete('company')
145
+ metadata = body.delete('metadata')
146
+ key = RouteTable.idempotency_key_of(name, body, idempotency_key)
147
+ body['idempotencyKey'] = key.strip if key.is_a?(String) && !key.strip.empty?
148
+ body['sessionType'] = RouteValue.one_of!(body['sessionType'].to_s.upcase, KycSessionType::ALL, 'sessionType') if body.key?('sessionType')
149
+ customer!(name, body, person, company)
150
+ evidence_context!(name, body, metadata)
151
+ check_session_fields!(body)
152
+ [body, key]
153
+ end
154
+
155
+ def customer!(name, body, person, company)
156
+ given = [person, company, body['customer']].compact
157
+ raise ConfigurationError, "#{name} takes one of person, company or customer." if given.length > 1
158
+
159
+ body['customer'] = { 'customerType' => 'PERSON' }.merge(nested!(person, 'person')) unless person.nil?
160
+ body['customer'] = { 'customerType' => 'COMPANY' }.merge(nested!(company, 'company')) unless company.nil?
161
+ end
162
+
163
+ def evidence_context!(name, body, metadata)
164
+ return if metadata.nil?
165
+ raise ConfigurationError, "#{name} takes metadata or evidenceContextJson, not both." if body.key?('evidenceContextJson')
166
+
167
+ body['evidenceContextJson'] = JsonBody.dump(nested!(metadata, 'metadata'))
168
+ end
169
+
170
+ def check_session_fields!(body)
171
+ if body.key?('ttlMinutes')
172
+ ttl = body['ttlMinutes']
173
+ unless ttl.is_a?(Integer) && ttl.between?(1, KYC_SESSION_TTL_MAX_MINUTES)
174
+ raise ConfigurationError, "'ttlMinutes' must be an integer from 1 to #{KYC_SESSION_TTL_MAX_MINUTES}."
175
+ end
176
+ end
177
+ types = body['requiredDocumentTypes']
178
+ return if types.nil? || (types.is_a?(Array) && types.all?(String))
179
+
180
+ raise ConfigurationError, "'requiredDocumentTypes' must be an array of document types."
181
+ end
182
+
183
+ def nested!(value, field)
184
+ raise ConfigurationError, "'#{field}' must be a Hash." unless value.is_a?(Hash)
185
+
186
+ value.transform_keys(&:to_s)
187
+ end
188
+ end
189
+ end