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
@@ -5,6 +5,8 @@ module Lunixi
5
5
  # documented endpoints without pretending to validate their entire DTO schema.
6
6
  class Payments
7
7
  BASE = '/api/v1/payments'
8
+ BIN_BASE = '/api/v1/bin'
9
+ PDF_ACCEPT = 'application/pdf, application/json'
8
10
  OMITTED_AMOUNT = Object.new.freeze
9
11
  private_constant :OMITTED_AMOUNT
10
12
  attr_reader :client
@@ -18,8 +20,9 @@ module Lunixi
18
20
  # Optional +enabledInstallments+ (an Array of Integer) lists the installment counts the hosted
19
21
  # form may offer for this payment, e.g. <tt>[1, 2, 3]</tt>; <tt>[1]</tt> allows a single payment
20
22
  # only. The form shows only the counts also allowed by the panel settings, the card and the
21
- # platform maximum. Leave it out for no restriction. Send distinct integers 1–36 that include 1,
22
- # in ascending order; the gateway rejects any other list, an empty one included, with 400.
23
+ # platform maximum. Leave it out for no restriction. The list must hold distinct integers 1–36
24
+ # that include 1; any other list, an empty one included, raises ConfigurationError before sending,
25
+ # and the list is sent in ascending order.
23
26
  #
24
27
  # @param body [Hash] gateway body: +amount+ (canonical minor-unit string), +currency+, +orderId+
25
28
  # and optional fields such as +callbackUrl+ and +enabledInstallments+
@@ -32,6 +35,66 @@ module Lunixi
32
35
  client.request('POST', "#{BASE}/intents", body: body, idempotency_key: Client.idempotency_key!(idempotency_key))
33
36
  end
34
37
 
38
+ # Create a marketplace intent (POST /payments/marketplace/intents, signed): the intent body plus
39
+ # sellers [{ subDealerId, amountMinor, scenario }] and multiSellerPolicy. Each amountMinor is a
40
+ # canonical minor-unit string and the sellers must add up to amount; any other total raises
41
+ # ConfigurationError before sending.
42
+ def create_marketplace_intent(body, idempotency_key:)
43
+ data = payment_body!(body)
44
+ sellers!(data['sellers'], data['amount'])
45
+ client.request('POST', "#{BASE}/marketplace/intents", body: data, idempotency_key: Client.idempotency_key!(idempotency_key))
46
+ end
47
+
48
+ # Card and bank details of a BIN (6 or 8 digits) or a card number prefix (POST /bin/info). The
49
+ # value is never written to an error message.
50
+ def bin_info(bin_or_pan)
51
+ client.request('POST', "#{BIN_BASE}/info", body: { 'binOrPan' => CardRules.bin_or_pan!(bin_or_pan) }, signed: false)
52
+ end
53
+
54
+ # The installment table (POST /bin/installments) for an InstallmentOptionsRequest or a raw Hash; with
55
+ # a BIN and installment > 1 the answer carries the binding quoteToken. enabledInstallments follows
56
+ # the rule of create_intent and is sent in ascending order.
57
+ def installment_options(body_or_request)
58
+ client.request('POST', "#{BIN_BASE}/installments", body: CardRules.installment_options_body!(body_or_request), signed: false)
59
+ end
60
+
61
+ # Brand, family and bank reference lists (GET /bin/card-taxonomy).
62
+ def card_taxonomy
63
+ client.request('GET', "#{BIN_BASE}/card-taxonomy", signed: false)
64
+ end
65
+
66
+ # Verify and store a card for a cardUserKey (POST /payments/cards, signed). Build the body with
67
+ # StoreCardRequest or pass a raw Hash; the idempotency key is required.
68
+ def store_card(body_or_request, idempotency_key: nil)
69
+ body = CardRules.store_card_body!(body_or_request)
70
+ client.request('POST', "#{BASE}/cards", body: body, idempotency_key: Client.idempotency_key!(idempotency_key))
71
+ end
72
+
73
+ # Stored cards of a cardUserKey (GET /payments/cards?cardUserKey=); masked card data only.
74
+ def list_stored_cards(card_user_key)
75
+ client.request('GET', "#{BASE}/cards", query: { cardUserKey: CardRules.text!(card_user_key, 'cardUserKey') }, signed: false)
76
+ end
77
+
78
+ def get_stored_card(stored_card_token)
79
+ client.request('GET', "#{BASE}/cards/#{identifier!(stored_card_token)}", signed: false)
80
+ end
81
+
82
+ # Deactivate a stored card (DELETE /payments/cards/{token}, signed); the idempotency key is required.
83
+ def deactivate_stored_card(stored_card_token, idempotency_key: nil)
84
+ client.request('DELETE', "#{BASE}/cards/#{identifier!(stored_card_token)}", idempotency_key: Client.idempotency_key!(idempotency_key))
85
+ end
86
+
87
+ # Payments rescued by provider failover retries (GET /payments/analytics/failover-recovery).
88
+ # Filters such as from, to or range are sent as the query.
89
+ def failover_recovery_analytics(**filters)
90
+ client.request('GET', "#{BASE}/analytics/failover-recovery", query: filters, signed: false)
91
+ end
92
+
93
+ # Performance of one provider credential (GET /payments/analytics/provider-credentials/{id}).
94
+ def provider_credential_analytics(credential_id, **filters)
95
+ client.request('GET', "#{BASE}/analytics/provider-credentials/#{identifier!(credential_id)}", query: filters, signed: false)
96
+ end
97
+
35
98
  # @return [Hash] Authenticated payment status envelope for reconciliation.
36
99
  def get(payment_id)
37
100
  client.request('GET', "#{BASE}/#{identifier!(payment_id)}", signed: false)
@@ -42,11 +105,69 @@ module Lunixi
42
105
  client.request('GET', BASE, query: filters, signed: false)
43
106
  end
44
107
 
45
- # Return merchant-enabled methods; the shared Lunixi form owns the final available list.
108
+ # Return merchant-enabled methods; the shared Lunixi form owns the final available list. Each method
109
+ # lists its blockName, providerSelection, providerSelectionMode and providers with the inputFields
110
+ # of the method block. payment_method narrows the list to one method code (QR is sent as QR_CODE).
46
111
  def methods(payment_method: nil)
47
- query = payment_method ? { paymentMethod: payment_method } : {}
112
+ query = payment_method.nil? ? {} : { paymentMethod: MethodFields.normalize_payment_method(payment_method) }
48
113
  client.request('GET', "#{BASE}/methods", query: query)
49
114
  end
115
+ alias list_payment_methods methods
116
+
117
+ # Start a payment with any method from the merchant server (POST /payments/direct/payment). Build
118
+ # the body with DirectMethodPaymentRequest or pass a raw Hash; both are checked before sending.
119
+ # When the buyer must act, data.action says how (PaymentActionType); a BANK_TRANSFER payment
120
+ # answers with a DISPLAY action read by BankTransferInstruction.from_response.
121
+ def direct_method_payment(body_or_request, idempotency_key: nil)
122
+ body = body_or_request.is_a?(DirectMethodPaymentRequest) ? body_or_request.to_h : DirectMethodPaymentRequest.payload!(body_or_request)
123
+ client.request('POST', "#{BASE}/direct/payment", body: body, idempotency_key: Client.idempotency_key!(idempotency_key))
124
+ end
125
+
126
+ # Complete the open action of a payment with { otp:, consentAccepted:, fields: } (at least one).
127
+ def confirm_payment_action(payment_id, action_id, input)
128
+ client.request('POST', action_path(payment_id, action_id, 'confirm'), body: MethodFields.confirm_body!(input))
129
+ end
130
+
131
+ # Send a new one-time code; the previous action is closed, confirm with the new data.action.id.
132
+ def resend_payment_action(payment_id, action_id)
133
+ client.request('POST', action_path(payment_id, action_id, 'resend'))
134
+ end
135
+
136
+ # The notes of a promissory-note payment with their status (PromissoryNoteStatus).
137
+ def get_promissory_notes(payment_id)
138
+ client.request('GET', promissory_notes_path(payment_id))
139
+ end
140
+
141
+ # Cancel notes; without serial_numbers every open note is cancelled. cancelResults[] gives the
142
+ # result per note (PromissoryNoteCancelResult, PromissoryNoteCancelErrorCode).
143
+ def cancel_promissory_notes(payment_id, serial_numbers: nil, idempotency_key: nil)
144
+ body = serial_numbers.nil? ? nil : { 'serialNumbers' => PromissoryNotePlan.serial_numbers!(serial_numbers) }
145
+ key = idempotency_key.nil? ? nil : Client.idempotency_key!(idempotency_key)
146
+ client.request('POST', "#{promissory_notes_path(payment_id)}/cancel", body: body, idempotency_key: key)
147
+ end
148
+
149
+ # The printable notes as PDF bytes (a frozen binary String), one note per page. Not stored by the
150
+ # gateway: download it when you need it. locale is one of PromissoryNoteDocumentLocale::ALL.
151
+ def download_promissory_note_document(payment_id, locale: nil)
152
+ query = locale.nil? ? {} : { locale: PromissoryNotePlan.document_locale!(locale) }
153
+ client.request('GET', "#{promissory_notes_path(payment_id)}/document", query: query, binary: true, accept: PDF_ACCEPT)
154
+ end
155
+
156
+ # Late, short and excess transfers of BANK_TRANSFER payments; data.items[] of the envelope.
157
+ def list_bank_transfer_exceptions(environment: nil, status: nil, limit: nil)
158
+ query = BankTransferExceptions.query!(environment: environment, status: status, limit: limit)
159
+ client.request('GET', "#{BASE}/bank-transfer/exceptions", query: query)
160
+ end
161
+
162
+ # Accept a LATE or UNDERPAID exception; data is the exception or nil.
163
+ def accept_bank_transfer_exception(exception_id)
164
+ client.request('POST', "#{BASE}/bank-transfer/exceptions/#{BankTransferExceptions.exception_id!(exception_id)}/accept")
165
+ end
166
+
167
+ # Report that you refunded the money of an exception to the sender from your own bank.
168
+ def mark_bank_transfer_exception_refunded(exception_id)
169
+ client.request('POST', "#{BASE}/bank-transfer/exceptions/#{BankTransferExceptions.exception_id!(exception_id)}/refunded")
170
+ end
50
171
 
51
172
  # Omit amount to capture the remaining authorization; explicit nil is invalid.
52
173
  def capture(payment_id, idempotency_key:, amount: OMITTED_AMOUNT)
@@ -77,9 +198,10 @@ module Lunixi
77
198
  legs = data['legs']
78
199
  raise ConfigurationError, 'Split payment requires 1–5 legs' unless legs.is_a?(Array) && legs.size.between?(1, 5)
79
200
 
80
- total = legs.sum do |leg|
201
+ total = legs.each_with_index.sum do |leg, index|
81
202
  raise ConfigurationError, 'Split legs must be objects' unless leg.is_a?(Hash)
82
203
 
204
+ SplitPaymentRules.leg!(leg, "legs[#{index}]")
83
205
  minor!(leg['amount']).to_i
84
206
  end
85
207
  raise ConfigurationError, 'Split leg amounts must equal totalAmount' unless total == data['totalAmount'].to_i
@@ -92,6 +214,12 @@ module Lunixi
92
214
  client.request('GET', "#{BASE}/split/#{identifier!(split_id)}", signed: false)
93
215
  end
94
216
 
217
+ # Split payments, newest first. Filters: LIST_SPLIT_PAYMENTS_FILTERS; status and currency take a
218
+ # value or a list, limit is 1–100 and after is the pageInfo.endCursor of the previous page.
219
+ def list_splits(**filters)
220
+ client.request('GET', "#{BASE}/split", query: SplitPaymentRules.list_query!(filters), signed: false)
221
+ end
222
+
95
223
  # Refund a split session using the documented partial/full amount in minor units.
96
224
  def refund_split(split_id, amount:, idempotency_key:, reason: nil)
97
225
  body = { 'amount' => minor!(amount) }
@@ -102,6 +230,14 @@ module Lunixi
102
230
 
103
231
  private
104
232
 
233
+ def action_path(payment_id, action_id, operation)
234
+ "#{BASE}/#{identifier!(payment_id)}/actions/#{identifier!(action_id)}/#{operation}"
235
+ end
236
+
237
+ def promissory_notes_path(payment_id)
238
+ "#{BASE}/#{identifier!(payment_id)}/promissory-notes"
239
+ end
240
+
105
241
  def identifier!(value)
106
242
  raise ConfigurationError, 'Invalid resource identifier' unless value.is_a?(String) && value.match?(/\A[a-zA-Z0-9_-]{1,256}\z/)
107
243
 
@@ -147,9 +283,22 @@ module Lunixi
147
283
  raise ConfigurationError, 'preauth must be a JSON boolean' if data.key?('preauth') && ![true, false].include?(data['preauth'])
148
284
 
149
285
  validate_basket!(data['basketItems'], data['amount']) if data.key?('basketItems')
286
+ data['enabledInstallments'] = EnabledInstallments.check!(data['enabledInstallments']) if data.key?('enabledInstallments')
150
287
  data
151
288
  end
152
289
 
290
+ def sellers!(sellers, amount)
291
+ raise ConfigurationError, 'Marketplace intent requires a nonempty sellers array' unless sellers.is_a?(Array) && !sellers.empty?
292
+
293
+ total = sellers.each_with_index.sum do |seller, index|
294
+ raise ConfigurationError, "sellers[#{index}] must be an object" unless seller.is_a?(Hash)
295
+
296
+ text!(seller['subDealerId'])
297
+ Money.minor(seller['amountMinor'], positive: false).to_i
298
+ end
299
+ raise ConfigurationError, 'sellers[].amountMinor must add up to amount' unless total == amount.to_i
300
+ end
301
+
153
302
  def validate_callback!(url)
154
303
  uri = URI.parse(url)
155
304
  raise ConfigurationError, 'callbackUrl must use HTTPS' unless uri.is_a?(URI::HTTPS) && uri.host && !uri.userinfo && !uri.fragment && url.bytesize <= 2048
@@ -0,0 +1,183 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Physical POS: payments on your card terminals, transactions, reports, end-of-day runs and results
5
+ # (/api/v1/physical-pos). Every call is signed; the signing key decides the environment (a TEST key
6
+ # can read, but every payment write is 403 physical_pos.environment.test_key_read_only). Payment
7
+ # writes need the physical_pos:payments scope; reads physical_pos:view or physical_pos:payments.
8
+ #
9
+ # Card data is never sent: the card is read on the device. A field that looks like card data (pan,
10
+ # cardNumber, cvv, expiry …) or a card number in merchantReference, an item name / tax group or a
11
+ # free-text filter raises PhysicalPosCardDataRejectedError before anything is sent; any other unknown
12
+ # field raises ConfigurationError. Body and filter keys are the wire names (String or Symbol;
13
+ # snake_case is accepted too). Amounts are canonical minor-unit strings ("4500"); counts and rates
14
+ # are numbers.
15
+ #
16
+ # A payment write is asynchronous: the answer means "accepted", not "paid". Follow the outcome with
17
+ # the physical_pos.payment.* webhooks or get_payment. A payment under manual review is resolved in
18
+ # the panel only.
19
+ #
20
+ # Idempotency: store the key first, then call.
21
+ #
22
+ # key = Lunixi::PhysicalPos.new_idempotency_key
23
+ # order.update!(pos_key: key) # your storage
24
+ # begin
25
+ # lunixi.physical_pos.create_payment(request, idempotency_key: key)
26
+ # rescue Lunixi::PhysicalPosOutcomeUnknownError
27
+ # # the payment may exist: call again later with the SAME key
28
+ # end
29
+ #
30
+ # A new key for the same payment can charge the card twice. For a SALE also send merchantReference
31
+ # with allowDuplicateReference: false; the gateway then refuses a second sale while one with that
32
+ # reference is unresolved (physical_pos.payment.previous_outcome_unknown).
33
+ class PhysicalPos
34
+ NEW_PAYMENT = ->(replayed) { replayed ? 200 : 202 }
35
+ OK = ->(_replayed) { 200 }
36
+
37
+ # A new Idempotency-Key (UUID v4). Store it with your order before you call.
38
+ def self.new_idempotency_key
39
+ PhysicalPosIdentifiers.new_idempotency_key
40
+ end
41
+
42
+ # Verifies (signature, event id, timestamp) and reads a physical_pos.* webhook from the raw body,
43
+ # the headers and your webhook secret (or a WebhookVerifier). See PhysicalPosWebhook.parse.
44
+ def self.parse_webhook_event(raw_body, headers, secret_or_verifier, tolerance: 300)
45
+ PhysicalPosWebhook.parse(raw_body, headers, secret_or_verifier, tolerance: tolerance)
46
+ end
47
+
48
+ def initialize(gateway)
49
+ @gateway = gateway
50
+ end
51
+
52
+ # Starts a payment on a device: SALE, PREAUTH_OPEN or REFUND_UNMATCHED (POST /payments). target is
53
+ # exactly one of { deviceId }, { vendorCode, serialNumber } or { externalRef }; items carry a
54
+ # taxGroupCode per line.
55
+ #
56
+ # instrument is CARD (default) or a provider-collected card such as MEAL_CARD; for those send
57
+ # interaction (INSTRUMENT_READ: the device reads the card, CODE_DISPLAY: the device shows the
58
+ # provider's QR / short code) and, when the terminal has several provider rows, terminalProviderId
59
+ # (a list_terminal_providers row id). Leave both out for CARD.
60
+ #
61
+ # idempotency_key is required. Returns a PhysicalPosWriteResult: 202 with paymentStatus NOT_STARTED
62
+ # for a new payment, 200 with replayed true when the same key and body were sent before (the
63
+ # payment's current view). Raises PhysicalPosOutcomeUnknownError when the outcome is unknown.
64
+ def create_payment(request, idempotency_key: nil)
65
+ key = PhysicalPosIdentifiers.required_idempotency_key!(idempotency_key, 'a physical POS payment')
66
+ body = PhysicalPosRequest.body!(request, PHYSICAL_POS_REQUEST_FIELDS['createPayment'], 'createPayment request')
67
+ @gateway.payment_write('/payments', body, key, NEW_PAYMENT)
68
+ end
69
+
70
+ # Reverses an approved payment (POST /payments/{paymentId}/reversals): VOID, REFUND (by amountMinor
71
+ # or by items: [{ lineNo, quantityMilli }]), PREAUTH_CLOSE or PREAUTH_CANCEL. The reversal is a new
72
+ # child payment (originalPaymentId = payment_id) followed like any payment. idempotency_key is
73
+ # required; same result and errors as create_payment.
74
+ def create_reversal(payment_id, request, idempotency_key: nil)
75
+ path = "/payments/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}/reversals"
76
+ key = PhysicalPosIdentifiers.required_idempotency_key!(idempotency_key, 'a physical POS reversal')
77
+ body = PhysicalPosRequest.body!(request, PHYSICAL_POS_REQUEST_FIELDS['createReversal'], 'createReversal request')
78
+ @gateway.payment_write(path, body, key, NEW_PAYMENT)
79
+ end
80
+
81
+ # Cancels a payment before its start command reaches the device (POST /payments/{paymentId}/cancel,
82
+ # 200). Read payment['paymentStatus']: only EXPIRED with statusReason
83
+ # MERCHANT_CANCELLED_BEFORE_DISPATCH means it was cancelled; a payment already in a final state
84
+ # comes back unchanged with replayed true. To undo an approved sale use a reversal. Cancelling is
85
+ # idempotent, so the key is optional (a new UUID when nil).
86
+ def cancel_payment(payment_id, idempotency_key: nil)
87
+ path = "/payments/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}/cancel"
88
+ @gateway.payment_write(path, {}, PhysicalPosIdentifiers.idempotency_key_or_new(idempotency_key), OK)
89
+ end
90
+
91
+ # One payment with its items and refund items (GET /payments/{paymentId}).
92
+ def get_payment(payment_id)
93
+ @gateway.record('GET', "/payments/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}", 'payment')
94
+ end
95
+
96
+ # Payments, newest first (GET /payments). Roots and reversals are in one list; items and
97
+ # refundItems are empty here (read one payment for them). merchantReference finds a payment after
98
+ # an unknown outcome.
99
+ def list_payments(**filters)
100
+ @gateway.page('/payments', PhysicalPosFilters.query!(filters, 'listPayments'))
101
+ end
102
+
103
+ def iterate_payments(**filters, &block)
104
+ PhysicalPosResponses.each_item(filters, block) { |query| list_payments(**query) }
105
+ end
106
+
107
+ # Transaction trees (root payment + its reversals), newest first (GET /transactions).
108
+ def list_transactions(**filters)
109
+ @gateway.page('/transactions', PhysicalPosFilters.query!(filters, 'listTransactions'))
110
+ end
111
+
112
+ def iterate_transactions(**filters, &block)
113
+ PhysicalPosResponses.each_item(filters, block) { |query| list_transactions(**query) }
114
+ end
115
+
116
+ # The tree of a root or child payment with its timeline (GET /transactions/{paymentId}).
117
+ def get_transaction(payment_id)
118
+ @gateway.record('GET', "/transactions/#{PhysicalPosIdentifiers.path_id(payment_id, 'paymentId')}", 'transaction')
119
+ end
120
+
121
+ # Payments with an unknown outcome or under manual review (GET /transactions/ambiguous).
122
+ def list_ambiguous_payments(**filters)
123
+ @gateway.page('/transactions/ambiguous', PhysicalPosFilters.query!(filters, 'listAmbiguousPayments'))
124
+ end
125
+
126
+ def iterate_ambiguous_payments(**filters, &block)
127
+ PhysicalPosResponses.each_item(filters, block) { |query| list_ambiguous_payments(**query) }
128
+ end
129
+
130
+ # Sale / refund / void counts and amounts with net per currency (GET /reports/sales-summary).
131
+ # dateFrom / dateTo are business days (YYYY-MM-DD, Europe/Istanbul); groupBy DAY, STORE, DEVICE or
132
+ # INSTRUMENT.
133
+ def get_sales_summary(**filters)
134
+ @gateway.data('GET', '/reports/sales-summary', query: PhysicalPosFilters.query!(filters, 'getSalesSummary'))
135
+ end
136
+
137
+ # Tax breakdown with refunds and voids deducted (GET /reports/tax-summary).
138
+ def get_tax_summary(**filters)
139
+ @gateway.data('GET', '/reports/tax-summary', query: PhysicalPosFilters.query!(filters, 'getTaxSummary'))
140
+ end
141
+
142
+ # End-of-day results per bank line, with the reported / system / difference totals (GET /settlements).
143
+ def list_settlements(**filters)
144
+ @gateway.page('/settlements', PhysicalPosFilters.query!(filters, 'listSettlements'))
145
+ end
146
+
147
+ def iterate_settlements(**filters, &block)
148
+ PhysicalPosResponses.each_item(filters, block) { |query| list_settlements(**query) }
149
+ end
150
+
151
+ # Starts end-of-day (batch close) on a device (POST /devices/{deviceId}/settlement,
152
+ # physical_pos:payments). End-of-day cannot be undone. The answer means "accepted": the device
153
+ # reports the result later; follow it with get_settlement_run or list_settlements.
154
+ #
155
+ # Returns a PhysicalPosWriteResult (result['run'], 202 new / 200 replay). Pass the key you stored,
156
+ # or nil for a new UUID (returned as idempotency_key; after an unknown outcome call again with it).
157
+ # A TEST key is refused with 403 physical_pos.environment.test_key_read_only.
158
+ def start_settlement(device_id, idempotency_key: nil)
159
+ path = "/devices/#{PhysicalPosIdentifiers.path_id(device_id, 'deviceId')}/settlement"
160
+ @gateway.keyed_write(path, {}, idempotency_key, NEW_PAYMENT)
161
+ end
162
+
163
+ # End-of-day runs started by Lunixi (manual and scheduled), newest first (GET /settlement-runs).
164
+ # Filters: deviceId, source (MANUAL_API, MANUAL_PANEL, SCHEDULED), runStatus (PENDING, STARTED,
165
+ # SKIPPED, FAILED), createdFrom / createdTo, includeTotal.
166
+ def list_settlement_runs(**filters)
167
+ @gateway.page('/settlement-runs', PhysicalPosFilters.query!(filters, 'listSettlementRuns'))
168
+ end
169
+
170
+ def iterate_settlement_runs(**filters, &block)
171
+ PhysicalPosResponses.each_item(filters, block) { |query| list_settlement_runs(**query) }
172
+ end
173
+
174
+ # One end-of-day run with its command status and result state (GET /settlement-runs/{runId}).
175
+ def get_settlement_run(run_id)
176
+ @gateway.record('GET', "/settlement-runs/#{PhysicalPosIdentifiers.path_id(run_id, 'runId')}", 'run')
177
+ end
178
+
179
+ def inspect
180
+ '#<Lunixi::PhysicalPos>'
181
+ end
182
+ end
183
+ end
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # The gateway's card-data rules for physical POS requests: card-data field names (any depth of a body
5
+ # or filter set) and the refusal of card data, field names and card numbers in free text (read by
6
+ # PhysicalPosCardNumber). The card is read on the device; a request never carries card data.
7
+ module PhysicalPosCardData
8
+ NUMBER_TERMS = %w[pan pannumber cardpan cardnumber cardno cardnum cardnr ccnumber ccnum primaryaccountnumber].freeze
9
+ SECRET_TERMS = %w[
10
+ cvv cvv2 cvc cvc2 cvn cvn2 cav2 cvvcode cvccode cardcode securitycode cardverificationcode cardverificationvalue
11
+ track1 track2 track3 tracki trackii trackiii trackdata magstripe magneticstripe pinblock pincode pinnumber pindata
12
+ cardpin cardholderpin encryptedpin expdate expmonth expyear expmmyy expirydate expirymonth expiryyear expirymmyy
13
+ expirationdate expirationmonth expirationyear expiremonth expireyear cardexpiry cardexpiration
14
+ ].freeze
15
+ SUFFIX_TERMS = %w[
16
+ cardnumber pannumber primaryaccountnumber cvv cvv2 cvc cvc2 cvvcode securitycode track1 track2 trackdata pinblock
17
+ expmonth expyear expirydate expirymonth expiryyear expirationdate cardexpiry
18
+ ].freeze
19
+ WHOLE_KEY_TERMS = %w[track expiry expiration pin cid csc].freeze
20
+ MASK_TOKENS = %w[masked mask].freeze
21
+
22
+ # Term lists of the card-data key rule (the parity test compares them with the shared fixture).
23
+ KEY_RULE = {
24
+ 'numberTerms' => NUMBER_TERMS, 'secretTerms' => SECRET_TERMS, 'suffixTerms' => SUFFIX_TERMS,
25
+ 'wholeKeyTerms' => WHOLE_KEY_TERMS, 'maskTokens' => MASK_TOKENS
26
+ }.freeze
27
+
28
+ DIGIT_RUN_KEY_SOURCE = '[0-9](?:[ -]?[0-9]){12,}'
29
+ DIGIT_RUN_KEY = Regexp.new(DIGIT_RUN_KEY_SOURCE)
30
+ IDENTIFIER_KEY = /\A[A-Za-z_$][A-Za-z0-9_$]*\z/
31
+
32
+ CARD_DATA_TERMS = (NUMBER_TERMS + SECRET_TERMS).freeze
33
+ CARD_DATA_MESSAGE = 'Physical POS requests must not contain card data: the card is read on the device. Remove the field ' \
34
+ 'or value; do not send card numbers, expiry dates or security codes.'
35
+
36
+ module_function
37
+
38
+ def key_tokens(key)
39
+ key.to_s
40
+ .gsub(/([a-z0-9])([A-Z])/, '\1 \2')
41
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1 \2')
42
+ .gsub(/([A-Za-z])([0-9])/, '\1 \2')
43
+ .gsub(/([0-9])([A-Za-z])/, '\1 \2')
44
+ .downcase
45
+ .split(/[^a-z0-9]+/)
46
+ .reject(&:empty?)
47
+ end
48
+
49
+ # True when a field name is card data (pan, cardNumber, cvv, track2Data, expiryDate …).
50
+ def card_data_key?(key)
51
+ tokens = key_tokens(key)
52
+ return false if tokens.empty?
53
+ return true if WHOLE_KEY_TERMS.include?(tokens.join)
54
+
55
+ masked = tokens.any? { |token| MASK_TOKENS.include?(token) }
56
+ tokens.each_index.any? { |start| card_data_run?(tokens, start, masked) }
57
+ end
58
+
59
+ def card_data_run?(tokens, start, masked)
60
+ joined = +''
61
+ tokens[start..].any? do |token|
62
+ joined << token
63
+ next true if CARD_DATA_TERMS.include?(joined) && !(masked && NUMBER_TERMS.include?(joined))
64
+
65
+ SUFFIX_TERMS.any? { |term| joined.end_with?(term) && !(masked && NUMBER_TERMS.include?(term)) }
66
+ end
67
+ end
68
+
69
+ # Path of the first card-data key in a body or filter set (items[1].cvv), or nil. A key holding a
70
+ # 13+ digit run stops at the parent path. Values are not read here.
71
+ def find_card_data_field(value, root = '(body)')
72
+ stack = [[value, '']]
73
+ until stack.empty?
74
+ node, path = stack.pop
75
+ if node.is_a?(Array)
76
+ (node.size - 1).downto(0) { |index| stack << [node[index], "#{path}[#{index}]"] }
77
+ next
78
+ end
79
+ next unless node.is_a?(Hash)
80
+
81
+ keys = node.keys
82
+ keys.each do |key|
83
+ return path.empty? ? root : path if key.to_s.match?(DIGIT_RUN_KEY)
84
+ return child_path(path, key) if card_data_key?(key)
85
+ end
86
+ keys.reverse_each { |key| stack << [node[key], child_path(path, key)] }
87
+ end
88
+ nil
89
+ end
90
+
91
+ def child_path(path, key)
92
+ name = key.to_s
93
+ return "#{path}[?]" unless name.match?(IDENTIFIER_KEY)
94
+
95
+ path.empty? ? name : "#{path}.#{name}"
96
+ end
97
+
98
+ def card_data_rejected(field)
99
+ PhysicalPosCardDataRejectedError.new(status: 0, field: field, message: "#{CARD_DATA_MESSAGE} Field: #{field}.")
100
+ end
101
+
102
+ def reject_card_data!(value, root)
103
+ field = find_card_data_field(value, root)
104
+ raise card_data_rejected(field) unless field.nil?
105
+ end
106
+
107
+ # Card-number values in the free-text fields the gateway scans (the value never reaches the error).
108
+ def reject_card_numbers!(body)
109
+ raise card_data_rejected('merchantReference') if PhysicalPosCardNumber.contains_pan_like_value?(body['merchantReference'])
110
+
111
+ Array(body['items']).each_with_index do |item, index|
112
+ raise card_data_rejected("items[#{index}].name") if PhysicalPosCardNumber.contains_pan_like_value?(item['name'], PhysicalPosCardNumber::ITEM_TEXT)
113
+ raise card_data_rejected("items[#{index}].taxGroupCode") if PhysicalPosCardNumber.contains_pan_like_value?(item['taxGroupCode'])
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Card numbers written into the free-text values of a physical POS request (merchantReference, item
5
+ # names, tax groups, free-text filters). Not a public API.
6
+ module PhysicalPosCardNumber
7
+ PAN_CANDIDATE = /(?<![\p{L}\p{N}])(?<![\p{L}\p{N}]-)[0-9](?:[ -]?[0-9]){12,18}(?![\p{L}\p{N}])(?!-[\p{L}\p{N}])/
8
+ GTIN = /\A(?:[0-9]{8}|[0-9]{12,14})\z/
9
+
10
+ # contains_pan_like_value? modes: STRICT for every scanned field, ITEM_TEXT for item names (an
11
+ # unseparated 13 or 14 digit number with a valid GTIN check digit is a barcode, not a card).
12
+ STRICT = 'STRICT'
13
+ ITEM_TEXT = 'ITEM_TEXT'
14
+
15
+ module_function
16
+
17
+ # True when the text holds a stand-alone, Luhn-valid 13–19 digit number (plain, space or dash
18
+ # separated). In ITEM_TEXT mode a valid unseparated 13 or 14 digit GTIN is a barcode.
19
+ def contains_pan_like_value?(text, mode = STRICT)
20
+ return false unless text.is_a?(String)
21
+
22
+ utf8_text(text).scan(PAN_CANDIDATE).any? do |candidate|
23
+ digits = candidate.delete(' -')
24
+ next false unless digits.length.between?(13, 19)
25
+ next false if mode == ITEM_TEXT && digits == candidate && digits.length <= 14 && gtin_valid?(digits)
26
+
27
+ luhn_valid?(digits)
28
+ end
29
+ end
30
+
31
+ def utf8_text(text)
32
+ utf8 = text.encode(Encoding::UTF_8)
33
+ raise ConfigurationError, 'Physical POS request text must be valid UTF-8' unless utf8.valid_encoding?
34
+
35
+ utf8
36
+ rescue EncodingError
37
+ raise ConfigurationError, 'Physical POS request text must be valid UTF-8', cause: nil
38
+ end
39
+
40
+ def luhn_valid?(digits)
41
+ sum = 0
42
+ digits.reverse.each_char.with_index do |char, index|
43
+ digit = char.to_i
44
+ if index.odd?
45
+ digit *= 2
46
+ digit -= 9 if digit > 9
47
+ end
48
+ sum += digit
49
+ end
50
+ (sum % 10).zero?
51
+ end
52
+
53
+ def gtin_valid?(digits)
54
+ return false unless digits.match?(GTIN)
55
+
56
+ sum = 0
57
+ weight = 3
58
+ (digits.length - 2).downto(0) do |index|
59
+ sum += digits[index].to_i * weight
60
+ weight = weight == 3 ? 1 : 3
61
+ end
62
+ (10 - (sum % 10)) % 10 == digits[-1].to_i
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Device identity routes of PhysicalPosManagement (physical_pos:identity for writes). Mixed into
5
+ # PhysicalPosManagement; uses its request and path helpers.
6
+ module PhysicalPosDeviceIdentity
7
+ # The device's identity keys, fingerprints only (GET /devices/{deviceId}/keys). Each key: keyId,
8
+ # algorithm, keyStatus (ACTIVE | SUPERSEDED | REVOKED), enrolledVia (PAIRING | ACTIVATION_CODE |
9
+ # ROTATION), fingerprint, lineageRootKeyId, rotatedFromKeyId, activatedAt, supersededAt, revokedAt,
10
+ # revokeReason, rowVersion.
11
+ def list_device_keys(device_id, **filters)
12
+ @gateway.page("#{device_path(device_id)}/keys", query(filters, 'history'))
13
+ end
14
+
15
+ def iterate_device_keys(device_id, **filters, &block)
16
+ PhysicalPosResponses.each_item(filters, block) { |page| list_device_keys(device_id, **page) }
17
+ end
18
+
19
+ # Revokes a device key: { rowVersion (the key's), reasonCode }; reasonCode DEVICE_LOST,
20
+ # DEVICE_STOLEN, KEY_COMPROMISED, DEVICE_REPLACED, MERCHANT_REQUEST or OTHER.
21
+ # { 'key', 'lifecycleStatus', 'replayed' }.
22
+ def revoke_device_key(device_id, key_id, request)
23
+ @gateway.data('POST', "#{key_path(device_id, key_id)}/revoke", body: body(request, 'revokeDeviceKey'))
24
+ end
25
+
26
+ # Reverts an activation-code enrollment (revokes the key, suspends the device): { reasonCode };
27
+ # NOT_MY_DEVICE, SUSPECTED_PHISHING, WRONG_DEVICE or OTHER. { 'key', 'lifecycleStatus', 'replayed' }.
28
+ def revert_device_enrollment(device_id, key_id, request)
29
+ @gateway.data('POST', "#{key_path(device_id, key_id)}/revert-enrollment", body: body(request, 'revertDeviceEnrollment'))
30
+ end
31
+
32
+ # Revokes the device's open activation code: { reasonCode }; MERCHANT_REVOKED, DEVICE_LOST,
33
+ # DEVICE_STOLEN or OTHER. { 'deviceId', 'revokedAt', 'revokeReason' }.
34
+ def revoke_activation_code(device_id, request)
35
+ @gateway.data('POST', "#{device_path(device_id)}/activation-code/revoke", body: body(request, 'revokeActivationCode'))
36
+ end
37
+
38
+ private
39
+
40
+ def key_path(device_id, key_id)
41
+ "#{device_path(device_id)}/keys/#{id(key_id, 'keyId')}"
42
+ end
43
+ end
44
+ end