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
data/lib/lunixi/errors.rb CHANGED
@@ -11,14 +11,33 @@ module Lunixi
11
11
  class RedirectError < Error; end
12
12
 
13
13
  class ApiError < Error
14
- attr_reader :status, :code, :request_id, :retry_after
14
+ # The only error `details` keys kept from a gateway answer; each value is a short identifier or a number.
15
+ DETAIL_FIELDS = %w[field allowedOperation retryAfterSeconds].freeze
16
+ SAFE_DETAIL = /\A[a-zA-Z0-9_.:\[\]?-]{1,200}\z/
15
17
 
16
- def initialize(status:, code: nil, request_id: nil, retry_after: nil)
18
+ # details: the safe subset of the answer's details (DETAIL_FIELDS). idempotency_key: the key a
19
+ # physical POS write sent, so a retry can reuse it.
20
+ attr_reader :status, :code, :request_id, :retry_after, :details, :idempotency_key
21
+
22
+ def initialize(status:, code: nil, request_id: nil, retry_after: nil, details: nil, idempotency_key: nil, message: nil)
17
23
  @status = status
18
24
  @code = safe_identifier(code)
19
25
  @request_id = safe_identifier(request_id)
20
26
  @retry_after = retry_after
21
- super("Lunixi request failed (HTTP #{status})")
27
+ @details = self.class.safe_details(details)
28
+ @idempotency_key = idempotency_key
29
+ super(message || "Lunixi request failed (HTTP #{status})")
30
+ end
31
+
32
+ def self.safe_details(details)
33
+ return {}.freeze unless details.is_a?(Hash)
34
+
35
+ details.each_with_object({}) do |(name, value), safe|
36
+ key = name.to_s
37
+ next unless DETAIL_FIELDS.include?(key)
38
+
39
+ safe[key] = value if value.is_a?(Integer) || value.is_a?(Float) || (value.is_a?(String) && value.match?(SAFE_DETAIL))
40
+ end.freeze
22
41
  end
23
42
 
24
43
  private
@@ -31,4 +50,51 @@ module Lunixi
31
50
  class AuthenticationError < ApiError; end
32
51
  class ValidationError < ApiError; end
33
52
  class RateLimitError < ApiError; end
53
+
54
+ # Physical POS: a request carries card data (a PAN, track, expiry or security-code field, or a card
55
+ # number in merchantReference, an item name / tax group or a free-text filter). Raised locally before
56
+ # anything is sent (status 0), or for the gateway's 400 physical_pos.payment.card_data_rejected.
57
+ # field is the path of the offending field (items[1].cvv); the value never reaches the error.
58
+ class PhysicalPosCardDataRejectedError < ValidationError
59
+ CODE = 'physical_pos.payment.card_data_rejected'
60
+ attr_reader :field
61
+
62
+ def initialize(field: nil, **)
63
+ @field = field
64
+ super(code: CODE, **)
65
+ end
66
+ end
67
+
68
+ # Physical POS: 429 RATE_LIMITED (payment writes are limited per API key). retry_after is the
69
+ # Retry-After header in seconds, or details.retryAfterSeconds when the header is missing.
70
+ class PhysicalPosRateLimitError < RateLimitError; end
71
+
72
+ # Physical POS: the outcome of a payment write (start, reversal, cancel) is unknown; the payment may
73
+ # or may not exist. Raised when an attempt got no HTTP answer, a 2xx without a readable payment, or a
74
+ # 5xx that does not say "not started", and then for the whole call, whatever a later attempt answered
75
+ # (a 429 or 409 included). Call again with the same idempotency_key (an existing payment comes back
76
+ # with replayed: true), or look it up with list_payments(merchantReference:). A new key can start a
77
+ # second payment. status / code are the last HTTP answer's (0 / nil when there was none); attempts is
78
+ # the number of attempts made.
79
+ class PhysicalPosOutcomeUnknownError < ApiError
80
+ attr_reader :attempts
81
+
82
+ def initialize(attempts: nil, **)
83
+ @attempts = attempts
84
+ super(**)
85
+ end
86
+ end
87
+
88
+ # Physical POS: 409 physical_pos.payment.void_after_settlement. The payment is already in a device
89
+ # end-of-day and can no longer be voided; return the amount with a REFUND reversal on the same payment
90
+ # (with a new idempotency key). allowed_operation is details.allowedOperation (REFUND).
91
+ class PhysicalPosVoidAfterSettlementError < ApiError
92
+ CODE = 'physical_pos.payment.void_after_settlement'
93
+ attr_reader :allowed_operation
94
+
95
+ def initialize(allowed_operation: nil, **)
96
+ @allowed_operation = allowed_operation
97
+ super(code: CODE, **)
98
+ end
99
+ end
34
100
  end
data/lib/lunixi/fraud.rb CHANGED
@@ -7,8 +7,13 @@ module Lunixi
7
7
  paymentId payment bankTransfer cryptoTransfer walletOperation billPayment loanApplication payout
8
8
  customer device session merchant mobileApp telemetry metadata identitySnapshot identityAssertion].freeze
9
9
 
10
+ # Transaction event ingest (signed) and the persisted decision log.
11
+ attr_reader :events, :decisions
12
+
10
13
  def initialize(client)
11
14
  @client = client
15
+ @events = FraudEvents.new(client)
16
+ @decisions = FraudDecisions.new(client)
12
17
  end
13
18
 
14
19
  # Evaluate the documented fraud DTO; tenant identity comes from credentials.
@@ -21,14 +26,85 @@ module Lunixi
21
26
  @client.request('POST', '/api/v1/fraud/decisions/evaluate', body: data, signed: false)
22
27
  end
23
28
 
24
- # Record a signed transaction event with a persisted operation idempotency key.
29
+ # Record a signed transaction event with a persisted operation idempotency key; same as events.record.
25
30
  def record_event(body, idempotency_key:)
26
- unless body.is_a?(Hash) && %w[eventId subjectType eventType occurredAt].all? { |name| body[name] || body[name.to_sym] }
27
- raise ConfigurationError, 'Fraud event requires eventId, subjectType, eventType and occurredAt'
31
+ events.record(body, idempotency_key: idempotency_key)
32
+ end
33
+ end
34
+
35
+ # Transaction events (POST /fraud/events/transactions[/batch]). Both routes are signed: the signature
36
+ # binds the event to your merchant, so a body value cannot claim another one.
37
+ class FraudEvents
38
+ BASE = '/api/v1/fraud/events/transactions'
39
+ REQUIRED_FIELDS = %w[eventId subjectType eventType occurredAt].freeze
40
+ # The gateway rejects the whole batch above this size.
41
+ BATCH_LIMIT = 500
42
+
43
+ def initialize(client)
44
+ @client = client
45
+ end
46
+
47
+ # One event with eventId, subjectType, eventType and occurredAt. Retrying with the same eventId is
48
+ # deduplicated by the gateway.
49
+ def record(body, idempotency_key:)
50
+ event!(body, 'Fraud event')
51
+ @client.request('POST', BASE, body: body, idempotency_key: Client.idempotency_key!(idempotency_key))
52
+ end
53
+
54
+ # Up to BATCH_LIMIT events in one call, sent as a JSON array. The batch can succeed partially: read
55
+ # the per-event results in data.
56
+ def record_batch(events, idempotency_key:)
57
+ unless events.is_a?(Array) && !events.empty? && events.size <= BATCH_LIMIT
58
+ raise ConfigurationError, "Fraud event batch must be a nonempty array of at most #{BATCH_LIMIT} events"
28
59
  end
29
60
 
30
- @client.request('POST', '/api/v1/fraud/events/transactions', body: body,
31
- idempotency_key: Client.idempotency_key!(idempotency_key))
61
+ events.each_with_index { |event, index| event!(event, "events[#{index}]") }
62
+ @client.request('POST', "#{BASE}/batch", body: events, idempotency_key: Client.idempotency_key!(idempotency_key))
63
+ end
64
+
65
+ private
66
+
67
+ def event!(body, name)
68
+ return if body.is_a?(Hash) && REQUIRED_FIELDS.all? { |field| body[field] || body[field.to_sym] }
69
+
70
+ raise ConfigurationError, "#{name} requires #{REQUIRED_FIELDS.join(', ')}"
71
+ end
72
+ end
73
+
74
+ # Persisted fraud decisions (GET /fraud/decision-logs). Lists are the gateway envelope: data is the
75
+ # page of decisions and pageInfo (a sibling of data) carries hasMore and nextCursor.
76
+ class FraudDecisions
77
+ BASE = '/api/v1/fraud/decision-logs'
78
+ LIST_FILTERS = %w[paymentId decision integrationMode productContext limit cursor].freeze
79
+
80
+ def initialize(client)
81
+ @client = client
82
+ end
83
+
84
+ # Filters: LIST_FILTERS; pass the previous page's pageInfo.nextCursor as cursor.
85
+ def list(**filters)
86
+ data = filters.transform_keys(&:to_s)
87
+ unknown = data.keys - LIST_FILTERS
88
+ raise ConfigurationError, "fraud.decisions.list does not take #{unknown.join(', ')}; filters: #{LIST_FILTERS.join(', ')}" unless unknown.empty?
89
+
90
+ query = data.reject { |_, value| value.nil? || value == '' }
91
+ @client.request('GET', BASE, query: query, signed: false)
92
+ end
93
+
94
+ # One decision by its trace id.
95
+ def get(trace_id)
96
+ raise ConfigurationError, 'trace_id is required' unless trace_id.is_a?(String) && trace_id.match?(/\A[a-zA-Z0-9_-]{1,256}\z/)
97
+
98
+ @client.request('GET', "#{BASE}/#{trace_id}", signed: false)
99
+ end
100
+
101
+ # The most recent decision of a payment (a Hash), or nil when there is none.
102
+ def latest_for_payment(payment_id)
103
+ raise ConfigurationError, 'payment_id is required' unless payment_id.is_a?(String) && !payment_id.strip.empty?
104
+
105
+ page = list(paymentId: payment_id, limit: 1)
106
+ items = page['data']
107
+ items.is_a?(Array) && items.first.is_a?(Hash) ? items.first : nil
32
108
  end
33
109
  end
34
110
  end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Identity signals (/api/v1/identity, client.identity).
5
+ #
6
+ # Calls carry the access token only. The browser fingerprint SDK produces a traceId; your server reads
7
+ # the linked accounts of that trace and flags or blocks when the device is shared ("one person, many
8
+ # accounts", Lunixi::Identity.device_shared?).
9
+ #
10
+ # This is a signal surface: it carries risk flags, reason codes, similarity probabilities and the
11
+ # identity snapshot, not an allow / review / block verdict (that is the fraud decision). Bodies and
12
+ # filters are checked against IDENTITY_ROUTES before anything is sent. Calls return the envelope's data;
13
+ # list_sessions returns a Lunixi::ListPage.
14
+ class Identity
15
+ NESTED_FIELDS = %w[customer device session source account metadata].freeze
16
+
17
+ # True when the device of an account_links answer is shared by at least threshold accounts, counting
18
+ # the current one (linkedAccounts excludes it). With the default 2, a second account on the device
19
+ # trips it.
20
+ def self.device_shared?(account_links, threshold = 2)
21
+ linked = account_links.is_a?(Hash) && account_links['linkedAccounts'].is_a?(Array) ? account_links['linkedAccounts'].length : 0
22
+ linked + 1 >= [2, threshold].max
23
+ end
24
+
25
+ # The distinct linkReasons of an account_links answer's sessions (same_device_cluster,
26
+ # same_fingerprint ...).
27
+ def self.link_reasons(account_links)
28
+ sessions = account_links.is_a?(Hash) && account_links['sessions'].is_a?(Array) ? account_links['sessions'] : []
29
+ sessions.flat_map { |session| session.is_a?(Hash) && session['linkReasons'].is_a?(Array) ? session['linkReasons'] : [] }
30
+ .map(&:to_s).uniq
31
+ end
32
+
33
+ def initialize(client)
34
+ @routes = RouteTable.new(client, IDENTITY_ROUTES)
35
+ end
36
+
37
+ # Synchronous analysis: { subjectType?, subjectId?, productContext?, integrationMode?, customer?,
38
+ # device?, session?, source?, account?, metadata?, paymentId? }. Returns { traceId, analysisStatus,
39
+ # riskFlags, reasonCodes, identitySnapshot, ... }.
40
+ def analyze_sync(request)
41
+ @routes.data('analyzeSync', body: analyze_body(request))
42
+ end
43
+
44
+ # Queues the analysis and returns the traceId at once.
45
+ def analyze(request)
46
+ @routes.data('analyze', body: analyze_body(request))
47
+ end
48
+
49
+ # Other accounts seen on this device / fingerprint / IP (account keys hashed).
50
+ def account_links(trace_id)
51
+ @routes.data('accountLinks', params: { 'traceId' => trace_id })
52
+ end
53
+
54
+ def get_session(trace_id)
55
+ @routes.data('getSession', params: { 'traceId' => trace_id })
56
+ end
57
+
58
+ # Recent sessions of the same device-identity cluster.
59
+ def related_sessions(trace_id, limit: nil)
60
+ @routes.data('relatedSessions', params: { 'traceId' => trace_id }, query: RouteRequest.compact('limit' => limit))
61
+ end
62
+
63
+ # The session summary and its recorded lifecycle events.
64
+ def timeline(trace_id)
65
+ @routes.data('timeline', params: { 'traceId' => trace_id })
66
+ end
67
+
68
+ # Source domains ranked by repeated risky activity; filters days, limit.
69
+ def top_sources(**filters)
70
+ @routes.data('topSources', query: filters)
71
+ end
72
+
73
+ # Filters: fingerprintId, deviceId, paymentId, limit.
74
+ def list_sessions(**filters)
75
+ @routes.page('listSessions', query: filters)
76
+ end
77
+
78
+ def inspect
79
+ '#<Lunixi::Identity>'
80
+ end
81
+
82
+ private
83
+
84
+ def analyze_body(request)
85
+ body = RouteRequest.wire_hash!(request, 'analyze request')
86
+ NESTED_FIELDS.each do |field|
87
+ raise ConfigurationError, "'#{field}' must be a Hash." if body.key?(field) && !body[field].is_a?(Hash)
88
+ end
89
+ raise ConfigurationError, 'subjectType and subjectId go together.' unless body.key?('subjectType') == body.key?('subjectId')
90
+
91
+ body
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Identity (device and account-linking signals) routes (/api/v1/identity). The browser fingerprint SDK
5
+ # uses the publishable key (/identity/sdk/init), which is not here.
6
+
7
+ # Body of analyze / analyze_sync; the nested objects are forwarded as given.
8
+ IDENTITY_ANALYZE_FIELDS = %w[subjectType subjectId productContext integrationMode customer device session source account metadata
9
+ paymentId].freeze
10
+
11
+ identity_live = '/api/v1/identity/live-sessions'
12
+ route = lambda do |method, path, **extra|
13
+ RouteRequest.route(method, path, step_up: false, idempotency_key: 'none', **extra)
14
+ end
15
+
16
+ # Every identity route the SDK calls (access token only). The same table as the Node SDK's
17
+ # IDENTITY_ROUTES; the parity test compares it with the shared catalog.
18
+ IDENTITY_ROUTES = {
19
+ 'analyzeSync' => route.call('POST', "#{identity_live}/analyze-sync", optional: IDENTITY_ANALYZE_FIELDS),
20
+ 'analyze' => route.call('POST', "#{identity_live}/analyze", optional: IDENTITY_ANALYZE_FIELDS),
21
+ 'accountLinks' => route.call('GET', "#{identity_live}/:traceId/account-links"),
22
+ 'getSession' => route.call('GET', "#{identity_live}/:traceId"),
23
+ 'relatedSessions' => route.call('GET', "#{identity_live}/:traceId/related-sessions", query: %w[limit]),
24
+ 'timeline' => route.call('GET', "#{identity_live}/:traceId/timeline"),
25
+ 'topSources' => route.call('GET', "#{identity_live}/top-sources", query: %w[days limit]),
26
+ 'listSessions' => route.call('GET', identity_live, query: %w[fingerprintId deviceId paymentId limit])
27
+ }.freeze
28
+ end
@@ -0,0 +1,294 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Insurance (/api/v1/insurance, product INSURANCE_SERVICE): offer, sell and service insurance for your
5
+ # basket items, and submit leads for the types sold by request only.
6
+ #
7
+ # Every call is signed, reads included (401 AUTH_HEADERS_MISSING unsigned, 403 PRODUCT_NOT_ENABLED
8
+ # without the product). The key decides the environment. create_order, confirm_payment, issue_policy,
9
+ # cancel_order, refund_premium and create_lead require an Idempotency-Key (8–200 printable ASCII,
10
+ # checked before sending); create_quote and bind_payment take one optionally.
11
+ #
12
+ # Request fields and filters are checked before anything is sent (the gateway rejects an unknown field
13
+ # with 400). The field rules of an insurance type's own object (insured, tickets ...) are not repeated
14
+ # here: a violation comes back as 422 insurance.validation.invalid with every
15
+ # details.errors[{ field, reason }] at once. Amounts are canonical minor-unit strings.
16
+ #
17
+ # Answers are the envelope's data; lists return a Lunixi::ListPage; policy files are frozen bytes.
18
+ class Insurance
19
+ BASE = '/api/v1/insurance'
20
+ PDF_ACCEPT = 'application/pdf, application/json'
21
+ CSV_ACCEPT = 'text/csv, application/json'
22
+
23
+ # consent for create_order: the quote option's terms unchanged and the moment the buyer accepted
24
+ # them (a Time or an ISO 8601 string with a time zone, not in the future).
25
+ def self.consent_from_quote(option, accepted_at)
26
+ terms = option.is_a?(Hash) ? option['terms'] : nil
27
+ raise ConfigurationError, "The quote option has no 'terms': pass an option returned by create_quote or get_quote." unless terms.is_a?(Hash)
28
+
29
+ { 'termsVersion' => RouteValue.text!(terms['version'], 'terms.version'),
30
+ 'termsSha256' => RouteValue.text!(terms['sha256'], 'terms.sha256'),
31
+ 'acceptedAt' => RouteValue.iso_time!(accepted_at, 'acceptedAt') }
32
+ end
33
+
34
+ # The premium basket item for a payment that collects the premium of an order (premiumCollectedBy
35
+ # MERCHANT): id = orderId, itemType VIRTUAL, price = premiumAmount. Add it to the payment's basket next
36
+ # to the insured items and add the premium to the payment amount; it carries no insurance field. A
37
+ # PROVIDER order has none.
38
+ def self.premium_basket_item(order, name:, category1:, category2: nil)
39
+ raise ConfigurationError, 'order must be a Hash.' unless order.is_a?(Hash)
40
+ unless order['premiumCollectedBy'] == InsurancePremiumCollectedBy::MERCHANT
41
+ raise ConfigurationError, 'Only an order whose premium you collect (premiumCollectedBy MERCHANT) has a premium basket item.'
42
+ end
43
+
44
+ item = { 'id' => RouteValue.text!(order['orderId'], 'order.orderId'),
45
+ 'name' => RouteValue.text!(name, 'name'),
46
+ 'category1' => RouteValue.text!(category1, 'category1') }
47
+ item['category2'] = RouteValue.text!(category2, 'category2') unless category2.nil? || category2 == ''
48
+ item.merge('itemType' => 'VIRTUAL', 'price' => InsuranceRequest.positive_minor!(order['premiumAmount'], 'order.premiumAmount'))
49
+ end
50
+
51
+ def initialize(client)
52
+ @client = client
53
+ end
54
+
55
+ # I1. Insurance types offered for a payment's recorded basket; without paymentIntentId the types sold
56
+ # without a basket item. An empty list means insurance is not offered; it is not an error.
57
+ def list_products(**filters)
58
+ read('/products', InsuranceRequest.query!(filters, 'listProducts', %w[currency]))
59
+ end
60
+
61
+ # I2. Insurance types offered for basket items before the payment exists (read-only):
62
+ # { currency, insuranceType?, context: { items } }.
63
+ def search_products(request)
64
+ body = RouteRequest.wire_keys!(request, INSURANCE_PRODUCT_SEARCH_FIELDS, 'searchProducts request')
65
+ payload = { 'currency' => RouteValue.currency!(body['currency'], 'currency'), 'context' => context(body, required: true) }
66
+ payload['insuranceType'] = RouteValue.text!(body['insuranceType'], 'insuranceType') if RouteRequest.present?(body['insuranceType'])
67
+ write('/products', payload)
68
+ end
69
+
70
+ # I3. Reference codes of one kind (InsuranceReferenceKind), for the type fields that take a code.
71
+ def list_reference_values(kind, **filters)
72
+ path = "/reference/#{RouteRequest.path!(':kind', 'kind' => InsuranceRequest.reference_kind!(kind))}"
73
+ RouteResponse.page(@client.request('GET', BASE + path, query: InsuranceRequest.query!(filters, 'listReferenceValues')))
74
+ end
75
+
76
+ def iterate_reference_values(kind, **filters, &block)
77
+ InsuranceRequest.reference_kind!(kind)
78
+ RouteResponse.each_item(filters, block) { |query| list_reference_values(kind, **query) }
79
+ end
80
+
81
+ # I4. Prices an insurance type (HTTP 201): { insuranceType, schemaVersion, options[], excludedOptions[] }.
82
+ # The basket is a payment's recorded basket (paymentIntentId) or the items you will send in the payment
83
+ # (context.items), not both; neither for a type sold without a basket item. Every option has its own
84
+ # quoteId, terms and expiresAt. The Idempotency-Key is optional and only correlates traces.
85
+ def create_quote(request, idempotency_key: nil)
86
+ body = RouteRequest.wire_keys!(request, INSURANCE_QUOTE_FIELDS, 'createQuote request')
87
+ payment = RouteRequest.present?(body['paymentIntentId'])
88
+ items = RouteRequest.present?(body['context'])
89
+ if payment && items
90
+ raise ConfigurationError, "Send the basket either as 'paymentIntentId' (a payment that exists) or as 'context.items' (before the " \
91
+ 'payment), not both. Send neither for an insurance type sold without a basket item.'
92
+ end
93
+
94
+ payload = body.merge('insuranceType' => RouteValue.text!(body['insuranceType'], 'insuranceType'),
95
+ 'currency' => RouteValue.currency!(body['currency'], 'currency'))
96
+ payload['paymentIntentId'] = InsuranceRequest.uuid!(body['paymentIntentId'], 'paymentIntentId') if payment
97
+ payload['context'] = context(body, required: true) if items
98
+ merchant_order_id!(payload)
99
+ write('/quotes', RouteRequest.compact(payload), InsuranceRequest.optional_key(idempotency_key))
100
+ end
101
+
102
+ # I5. 404 insurance.quote.not_found for an unknown or another merchant's quote.
103
+ def get_quote(quote_id)
104
+ read("/quotes/#{segment(quote_id, 'quoteId')}")
105
+ end
106
+
107
+ # I6. Turns a quote option into an order (HTTP 201) and records the buyer's consent; no provider call,
108
+ # no money movement. consent carries the option's terms back unchanged (Insurance.consent_from_quote).
109
+ def create_order(request, idempotency_key: nil)
110
+ key = InsuranceRequest.required_key!(idempotency_key, 'insurance order create')
111
+ body = RouteRequest.wire_keys!(request, INSURANCE_ORDER_FIELDS, 'createOrder request')
112
+ consent = RouteRequest.wire_keys!(body['consent'], INSURANCE_CONSENT_FIELDS, 'consent')
113
+ payload = { 'quoteId' => RouteValue.text!(body['quoteId'], 'quoteId'), 'merchantOrderId' => body['merchantOrderId'],
114
+ 'consent' => { 'termsVersion' => RouteValue.text!(consent['termsVersion'], 'consent.termsVersion'),
115
+ 'termsSha256' => RouteValue.text!(consent['termsSha256'], 'consent.termsSha256'),
116
+ 'acceptedAt' => RouteValue.iso_time!(consent['acceptedAt'], 'consent.acceptedAt') } }
117
+ merchant_order_id!(payload)
118
+ write('/orders', RouteRequest.compact(payload), key)
119
+ end
120
+
121
+ # I7. Your insurance orders, newest first.
122
+ def list_orders(**filters)
123
+ RouteResponse.page(@client.request('GET', "#{BASE}/orders", query: InsuranceRequest.query!(filters, 'listOrders')))
124
+ end
125
+
126
+ def iterate_orders(**filters, &block)
127
+ RouteResponse.each_item(filters, block) { |query| list_orders(**query) }
128
+ end
129
+
130
+ # I8. 404 insurance.order.not_found for an unknown or another merchant's order.
131
+ def get_order(order_id)
132
+ read(order_path(order_id))
133
+ end
134
+
135
+ # I9. Binds an order to the Lunixi payment that collects its premium. With premiumCollectedBy MERCHANT
136
+ # the payment basket must hold the premium item (Insurance.premium_basket_item); with PROVIDER it must
137
+ # not. Binding the same payment again returns the order. The Idempotency-Key is optional.
138
+ def bind_payment(order_id, payment_intent_id, idempotency_key: nil)
139
+ body = { 'paymentIntentId' => InsuranceRequest.uuid!(payment_intent_id, 'paymentIntentId') }
140
+ write("#{order_path(order_id)}/bind-payment", body, InsuranceRequest.optional_key(idempotency_key))
141
+ end
142
+
143
+ # I10. Records a premium you collected outside Lunixi: { externalPaymentId, paidAmount, paidCurrency,
144
+ # paidAt, paymentProvider? }; paidAmount and paidCurrency must equal the order's premium.
145
+ def confirm_payment(order_id, payment, idempotency_key: nil)
146
+ key = InsuranceRequest.required_key!(idempotency_key, 'insurance payment confirmation')
147
+ body = RouteRequest.wire_keys!(payment, INSURANCE_EXTERNAL_PAYMENT_FIELDS, 'payment')
148
+ payload = { 'externalPaymentId' => RouteValue.text!(body['externalPaymentId'], 'payment.externalPaymentId', InsuranceRequest::TEXT_MAX_LENGTH),
149
+ 'paidAmount' => InsuranceRequest.positive_minor!(body['paidAmount'], 'payment.paidAmount'),
150
+ 'paidCurrency' => RouteValue.currency!(body['paidCurrency'], 'payment.paidCurrency'),
151
+ 'paidAt' => RouteValue.iso_time!(body['paidAt'], 'payment.paidAt') }
152
+ if RouteRequest.present?(body['paymentProvider'])
153
+ payload['paymentProvider'] = RouteValue.text!(body['paymentProvider'], 'payment.paymentProvider', InsuranceRequest::CODE_MAX_LENGTH)
154
+ end
155
+ write("#{order_path(order_id)}/confirm-payment", { 'payment' => payload }, key)
156
+ end
157
+
158
+ # I11. Requests the policy of an order whose premium you collected outside Lunixi (policyStatus
159
+ # PENDING; the result arrives by webhook). 412 insurance.premium.not_captured before collection.
160
+ def issue_policy(order_id, idempotency_key: nil)
161
+ write("#{order_path(order_id)}/issue-policy", nil, InsuranceRequest.required_key!(idempotency_key, 'insurance policy issue'))
162
+ end
163
+
164
+ # I12. Opens a cancellation at the provider for every issued policy (policyStatus CANCEL_PENDING;
165
+ # insurance.policy.cancelled confirms it). It does not refund the premium: call refund_premium after it.
166
+ def cancel_order(order_id, idempotency_key: nil)
167
+ write("#{order_path(order_id)}/cancel", nil, InsuranceRequest.required_key!(idempotency_key, 'insurance order cancel'))
168
+ end
169
+
170
+ # I13. Refunds the premium. With a Lunixi payment leave external_refund out (refundStatus PENDING, then
171
+ # insurance.refund.completed); for a premium collected outside Lunixi pass the refund you made:
172
+ # { externalRefundId, refundedAt }. An in-force policy must be cancelled first (409).
173
+ def refund_premium(order_id, external_refund: nil, idempotency_key: nil)
174
+ key = InsuranceRequest.required_key!(idempotency_key, 'insurance premium refund')
175
+ payload = {}
176
+ unless external_refund.nil?
177
+ refund = RouteRequest.wire_keys!(external_refund, INSURANCE_EXTERNAL_REFUND_FIELDS, 'externalRefund')
178
+ payload['externalRefund'] = {
179
+ 'externalRefundId' => RouteValue.text!(refund['externalRefundId'], 'externalRefund.externalRefundId', InsuranceRequest::TEXT_MAX_LENGTH),
180
+ 'refundedAt' => RouteValue.iso_time!(refund['refundedAt'], 'externalRefund.refundedAt')
181
+ }
182
+ end
183
+ write("#{order_path(order_id)}/refund-premium", payload, key)
184
+ end
185
+
186
+ # I14. The policy PDF as frozen bytes, read from the provider on every call while the policy is in
187
+ # force (ISSUED, CANCEL_PENDING); 503 insurance.document.unavailable is temporary.
188
+ def get_policy_document(policy_id)
189
+ policy_file(policy_id, 'document')
190
+ end
191
+
192
+ # I21. The provider's premium receipt as PDF bytes; 412 insurance.document.not_supported when the
193
+ # product issues none.
194
+ def get_policy_receipt(policy_id)
195
+ policy_file(policy_id, 'receipt')
196
+ end
197
+
198
+ # I22. The provider's certificate of the policy (for example a green card) as PDF bytes; 412
199
+ # insurance.document.not_supported when the product issues none.
200
+ def get_policy_certificate(policy_id)
201
+ policy_file(policy_id, 'certificate')
202
+ end
203
+
204
+ # I15. Reconciliation totals by provider connection, currency and premiumCollectedBy. from (inclusive)
205
+ # and to (exclusive) are required, on the order creation time, at most 366 days apart.
206
+ def get_reconciliation_summary(**filters)
207
+ read('/reconciliation/summary', InsuranceRequest.query!(filters, 'getReconciliationSummary', %w[from to]))
208
+ end
209
+
210
+ # I16. The orders and policies behind the summary for the same filter, newest first.
211
+ def list_reconciliation_orders(**filters)
212
+ query = InsuranceRequest.query!(filters, 'listReconciliationOrders', %w[from to])
213
+ RouteResponse.page(@client.request('GET', "#{BASE}/reconciliation/orders", query: query))
214
+ end
215
+
216
+ def iterate_reconciliation_orders(**filters, &block)
217
+ RouteResponse.each_item(filters, block) { |query| list_reconciliation_orders(**query) }
218
+ end
219
+
220
+ # I17. The reconciliation report as CSV: a Lunixi::InsuranceReconciliationExport (data bytes,
221
+ # truncated?, next_cursor, aborted?).
222
+ def export_reconciliation(**filters)
223
+ query = InsuranceRequest.query!(filters, 'exportReconciliation', %w[from to])
224
+ InsuranceRequest.export(@client.request('GET', "#{BASE}/reconciliation/export", query: query, binary: true, accept: CSV_ACCEPT))
225
+ end
226
+
227
+ # I18. Submits a lead (HTTP 201) for a type sold by request only: no premium, order, policy or
228
+ # document. status SUBMITTED (then insurance.lead.submitted) or UNKNOWN (not sent again). A provider
229
+ # refusal is 422 insurance.lead.rejected; a type or connection without leads 412
230
+ # insurance.type.not_available. The Idempotency-Key is required.
231
+ def create_lead(request, idempotency_key: nil)
232
+ key = InsuranceRequest.required_key!(idempotency_key, 'insurance lead submit')
233
+ body = RouteRequest.wire_keys!(request, INSURANCE_LEAD_FIELDS, 'createLead request')
234
+ payload = body.merge('insuranceType' => RouteValue.text!(body['insuranceType'], 'insuranceType', InsuranceRequest::CODE_MAX_LENGTH))
235
+ payload['note'] = InsuranceRequest.lead_note!(body['note']) if body.key?('note')
236
+ payload.delete('note') if payload['note'] == ''
237
+ write('/leads', payload, key)
238
+ end
239
+
240
+ # I19. Your leads, newest first; personal data is masked in requestMasked.
241
+ def list_leads(**filters)
242
+ RouteResponse.page(@client.request('GET', "#{BASE}/leads", query: InsuranceRequest.query!(filters, 'listLeads')))
243
+ end
244
+
245
+ def iterate_leads(**filters, &block)
246
+ RouteResponse.each_item(filters, block) { |query| list_leads(**query) }
247
+ end
248
+
249
+ # I20. 404 insurance.lead.not_found for an unknown or another merchant's lead.
250
+ def get_lead(lead_id)
251
+ read("/leads/#{segment(lead_id, 'leadId')}")
252
+ end
253
+
254
+ def inspect
255
+ '#<Lunixi::Insurance>'
256
+ end
257
+
258
+ private
259
+
260
+ def read(path, query = {})
261
+ RouteResponse.unwrap(@client.request('GET', BASE + path, query: query))
262
+ end
263
+
264
+ def write(path, body, key = nil)
265
+ RouteResponse.unwrap(@client.request('POST', BASE + path, body: body, idempotency_key: key))
266
+ end
267
+
268
+ def policy_file(policy_id, file)
269
+ @client.request('GET', "#{BASE}/policies/#{segment(policy_id, 'policyId')}/#{file}", binary: true, accept: PDF_ACCEPT)
270
+ end
271
+
272
+ def context(body, required:)
273
+ raise ConfigurationError, "'context.items' is required." if required && !RouteRequest.present?(body['context'])
274
+
275
+ InsuranceRequest.context!(body['context'])
276
+ end
277
+
278
+ def merchant_order_id!(payload)
279
+ if RouteRequest.present?(payload['merchantOrderId'])
280
+ payload['merchantOrderId'] = RouteValue.text!(payload['merchantOrderId'], 'merchantOrderId', InsuranceRequest::TEXT_MAX_LENGTH)
281
+ else
282
+ payload.delete('merchantOrderId')
283
+ end
284
+ end
285
+
286
+ def order_path(order_id)
287
+ "/orders/#{segment(order_id, 'orderId')}"
288
+ end
289
+
290
+ def segment(value, field)
291
+ RouteRequest.path!(":#{field}", field => value)
292
+ end
293
+ end
294
+ end