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,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+
5
+ module Lunixi
6
+ # Local checks of the physical POS list and report filters (PHYSICAL_POS_FILTERS).
7
+ module PhysicalPosFilters
8
+ AMOUNT_FILTERS = %w[amountFromMinor amountToMinor].freeze
9
+ CALENDAR_DAY_FILTERS = %w[dateFrom dateTo].freeze
10
+
11
+ module_function
12
+
13
+ # Checks list / report filters of a route (PHYSICAL_POS_FILTERS) and returns the query. nil and ''
14
+ # are left out. limit is 1–100; includeTotal a boolean; amountFromMinor / amountToMinor canonical
15
+ # minor-unit strings; a Time in createdFrom / createdTo is sent as ISO 8601 UTC; dateFrom / dateTo
16
+ # take a YYYY-MM-DD string, a Date or a Time (its own calendar day, not converted to
17
+ # Europe/Istanbul). merchantReference and q are scanned for card numbers.
18
+ def query!(filters, route)
19
+ return {} if filters.nil?
20
+
21
+ PhysicalPosCardData.reject_card_data!(filters, '(query)')
22
+ allowed = PHYSICAL_POS_FILTERS.fetch(route)
23
+ given = PhysicalPosRequest.wire_keys!(filters, allowed, 'physical POS', 'filter')
24
+ allowed.each_with_object({}) do |key, query|
25
+ next unless given.key?(key)
26
+
27
+ value = given[key]
28
+ next query[key] = PhysicalPosValue.money!(value, key) if AMOUNT_FILTERS.include?(key)
29
+ next if value.nil? || value == ''
30
+
31
+ query[key] = filter_value(key, value)
32
+ free_text = PHYSICAL_POS_FREE_TEXT_FILTERS.include?(key)
33
+ raise PhysicalPosCardData.card_data_rejected(key) if free_text && PhysicalPosCardNumber.contains_pan_like_value?(query[key])
34
+ end
35
+ end
36
+
37
+ def filter_value(key, value)
38
+ case key
39
+ when 'limit'
40
+ unless value.is_a?(Integer) && value.between?(1, PHYSICAL_POS_MAX_LIMIT)
41
+ raise ConfigurationError, "'limit' must be an integer between 1 and #{PHYSICAL_POS_MAX_LIMIT}."
42
+ end
43
+
44
+ value.to_s
45
+ when 'includeTotal' then PhysicalPosValue.boolean!(value, key) ? 'true' : 'false'
46
+ else time_filter(key, value)
47
+ end
48
+ end
49
+
50
+ def time_filter(key, value)
51
+ return value.strftime('%Y-%m-%d') if CALENDAR_DAY_FILTERS.include?(key) && (value.is_a?(Time) || value.is_a?(Date))
52
+ return value.getutc.strftime('%Y-%m-%dT%H:%M:%S.%LZ') if value.is_a?(Time)
53
+ raise ConfigurationError, "'#{key}' must be a string." unless value.is_a?(String)
54
+
55
+ value
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Sends the physical POS requests of PhysicalPos and PhysicalPosManagement through Client#request
5
+ # (signed, bearer token), checks the declared money of every answer and maps the errors. Payment
6
+ # writes run their own attempt loop so an uncertain outcome is never lost. Not a public API.
7
+ class PhysicalPosGateway
8
+ AMBIGUOUS = :ambiguous
9
+ NOT_STARTED = :not_started
10
+ DEFINITE = :definite
11
+ OUTCOME_UNKNOWN_MESSAGE = 'The outcome of the physical POS payment request is unknown: the payment may exist. Call again ' \
12
+ 'with the same idempotency_key (an existing payment comes back with replayed: true) or look ' \
13
+ 'it up; never use a new key for it.'
14
+
15
+ def initialize(client, max_retries:, backoff:)
16
+ @client = client
17
+ @max_retries = max_retries
18
+ @backoff = backoff
19
+ end
20
+
21
+ # One signed request (reads and management writes); answers are money-checked, errors mapped.
22
+ def perform(method, path, body: nil, query: {}, idempotency_key: nil)
23
+ response = @client.request(method, PhysicalPosRequest::BASE + path, body: body, query: query, idempotency_key: idempotency_key)
24
+ PhysicalPosMoney.validate(response)
25
+ response
26
+ rescue ApiError => e
27
+ mapped = PhysicalPosResponses.translate(e, idempotency_key)
28
+ raise if mapped.equal?(e)
29
+
30
+ raise mapped
31
+ end
32
+
33
+ def data(method, path, body: nil, query: {})
34
+ PhysicalPosResponses.unwrap(perform(method, path, body: body, query: query))
35
+ end
36
+
37
+ # data[name] of a single-record answer (or data when the wrapper is missing).
38
+ def record(method, path, name, body: nil, query: {})
39
+ PhysicalPosResponses.member(perform(method, path, body: body, query: query), name)
40
+ end
41
+
42
+ def page(path, query)
43
+ PhysicalPosResponses.page(perform('GET', path, query: query))
44
+ end
45
+
46
+ # A management or end-of-day write with an Idempotency-Key: the caller's key, or a new UUID for nil.
47
+ def keyed_write(path, body, idempotency_key, fallback)
48
+ key = PhysicalPosIdentifiers.idempotency_key_or_new(idempotency_key)
49
+ PhysicalPosResponses.write_result(perform('POST', path, body: body, idempotency_key: key), key, fallback)
50
+ end
51
+
52
+ # Payment start, reversal or cancel: 1 + max_retries attempts with the same key and body (the
53
+ # client's own retries are off for each attempt).
54
+ #
55
+ # Success is only a 2xx carrying a payment. A 2xx without a readable payment, no HTTP answer, or a
56
+ # 5xx that does not say "not started" leaves the outcome unknown; it is retried while attempts
57
+ # remain. A 4xx stops at once. When any attempt was ambiguous the call raises
58
+ # PhysicalPosOutcomeUnknownError whatever the last answer was (a later 429 or 409 included),
59
+ # because the key may already hold a payment.
60
+ def payment_write(path, body, key, fallback)
61
+ attempts = 1 + @max_retries
62
+ ambiguous = false
63
+ last_error = nil
64
+ (1..attempts).each do |attempt|
65
+ response, error, outcome = attempt_payment(path, body, key)
66
+ if response
67
+ result = written_payment(response, key, fallback)
68
+ return result if result
69
+
70
+ error = missing_payment(response)
71
+ outcome = AMBIGUOUS
72
+ end
73
+ local_error!(error, ambiguous, key, attempt) if outcome.nil?
74
+ last_error = error
75
+ ambiguous ||= outcome == AMBIGUOUS
76
+ if outcome == DEFINITE || attempt == attempts
77
+ raise outcome_unknown(last_error, key, attempt), cause: last_error if ambiguous
78
+
79
+ break
80
+ end
81
+ @backoff.call(attempt - 1)
82
+ end
83
+ definite!(last_error, key)
84
+ end
85
+
86
+ private
87
+
88
+ # [response, nil, nil] for an answer, [nil, error, outcome] for a failed attempt; outcome nil marks
89
+ # an error raised before anything was sent.
90
+ def attempt_payment(path, body, key)
91
+ response = @client.request('POST', PhysicalPosRequest::BASE + path, body: body, idempotency_key: key, max_retries: 0)
92
+ [response, nil, nil]
93
+ rescue ApiError => e
94
+ [nil, e, attempt_outcome(e)]
95
+ rescue StandardError => e
96
+ [nil, e, raised_before_sending?(e) ? nil : AMBIGUOUS]
97
+ end
98
+
99
+ # An SDK error other than a transport or redirect failure (a local check) means nothing was sent.
100
+ def raised_before_sending?(error)
101
+ error.is_a?(Error) && !error.is_a?(TransportError) && !error.is_a?(RedirectError)
102
+ end
103
+
104
+ # - ambiguous: no HTTP answer, an unreadable 2xx, or a 5xx that does not say "not started".
105
+ # - not_started: a 5xx with a code in PHYSICAL_POS_NOT_STARTED_CODES.
106
+ # - definite: any other answer (4xx, 429 and 409 included).
107
+ def attempt_outcome(error)
108
+ return AMBIGUOUS if error.status.to_i.zero? || error.status.to_i.between?(200, 299)
109
+ return DEFINITE if error.status.to_i < 500
110
+
111
+ PHYSICAL_POS_NOT_STARTED_CODES.include?(error.code) ? NOT_STARTED : AMBIGUOUS
112
+ end
113
+
114
+ # A local refusal (nothing sent) after an earlier uncertain attempt still leaves the outcome unknown.
115
+ def local_error!(error, ambiguous, key, attempt)
116
+ raise error unless ambiguous
117
+
118
+ raise outcome_unknown(error, key, attempt - 1), cause: error
119
+ end
120
+
121
+ def definite!(error, key)
122
+ mapped = PhysicalPosResponses.translate(error, key)
123
+ raise mapped if mapped.equal?(error)
124
+
125
+ raise mapped, cause: error
126
+ end
127
+
128
+ def missing_payment(response)
129
+ status = response.is_a?(Hash) && response['statusCode'].is_a?(Integer) ? response['statusCode'] : 0
130
+ ApiError.new(status: status, message: 'The gateway accepted the payment request but the answer carries no payment.')
131
+ end
132
+
133
+ def written_payment(response, key, fallback)
134
+ PhysicalPosMoney.validate(response)
135
+ data = PhysicalPosResponses.unwrap(response)
136
+ payment = data.is_a?(Hash) ? data['payment'] : nil
137
+ return nil unless payment.is_a?(Hash) && payment['paymentId'].is_a?(String) && !payment['paymentId'].empty?
138
+
139
+ PhysicalPosResponses.write_result(response, key, fallback)
140
+ rescue ConfigurationError, SystemStackError
141
+ nil
142
+ end
143
+
144
+ def outcome_unknown(last_error, key, attempts)
145
+ answered = last_error.is_a?(ApiError) ? last_error : nil
146
+ PhysicalPosOutcomeUnknownError.new(
147
+ status: answered ? answered.status : 0, code: answered&.code, request_id: answered&.request_id,
148
+ details: answered&.details, retry_after: answered ? PhysicalPosResponses.retry_after_seconds(answered) : nil,
149
+ idempotency_key: key, attempts: attempts, message: OUTCOME_UNKNOWN_MESSAGE
150
+ )
151
+ end
152
+ end
153
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module Lunixi
6
+ # The Idempotency-Key and the path identifiers of the physical POS requests. Not a public API.
7
+ module PhysicalPosIdentifiers
8
+ module_function
9
+
10
+ # ── Idempotency-Key ──────────────────────────────────────────────────────
11
+
12
+ # A new Idempotency-Key (UUID v4). Store it with your order before you call.
13
+ def new_idempotency_key
14
+ SecureRandom.uuid
15
+ end
16
+
17
+ # A key you pass is checked and sent exactly as given (never trimmed).
18
+ def idempotency_key!(key)
19
+ unless key.is_a?(String) && key.match?(PHYSICAL_POS_IDEMPOTENCY_KEY_PATTERN)
20
+ raise ConfigurationError, 'The Idempotency-Key must be 8–200 printable ASCII characters without spaces; it is sent exactly ' \
21
+ 'as given. Use a new UUID for every operation and the same key to retry it.'
22
+ end
23
+
24
+ key
25
+ end
26
+
27
+ # The key to send where the SDK may create one: the caller's key (checked) or a new UUID for nil.
28
+ def idempotency_key_or_new(key)
29
+ key.nil? ? new_idempotency_key : idempotency_key!(key)
30
+ end
31
+
32
+ # Payment start and reversal: the caller must pass the key (nothing is generated).
33
+ def required_idempotency_key!(key, operation)
34
+ if key.nil?
35
+ raise ConfigurationError, "A stable idempotency_key is required for #{operation}. Create one with " \
36
+ 'Lunixi::PhysicalPos.new_idempotency_key, store it with your order, then call; when the outcome ' \
37
+ 'is unknown call again with the SAME key.'
38
+ end
39
+
40
+ idempotency_key!(key)
41
+ end
42
+
43
+ # ── Identifiers ──────────────────────────────────────────────────────────
44
+
45
+ # A path segment: a non-empty String, not . or .., percent-encoded (everything but A-Z a-z 0-9 - _ . ~).
46
+ def path_id(value, field)
47
+ raise ConfigurationError, "'#{field}' must be a non-empty string." unless value.is_a?(String) && !value.empty?
48
+ raise ConfigurationError, "'#{field}' is not a valid identifier." if ['.', '..'].include?(value)
49
+
50
+ value.b.gsub(/[^A-Za-z0-9_.~-]/n) { |byte| format('%%%02X', byte.ord) }.force_encoding(Encoding::UTF_8)
51
+ end
52
+
53
+ def row_version!(value, field)
54
+ PhysicalPosValue.integer!(value, field)
55
+ unless value.between?(1, PHYSICAL_POS_ROW_VERSION_MAX)
56
+ raise ConfigurationError, "'#{field}' must be between 1 and #{PHYSICAL_POS_ROW_VERSION_MAX}: send the rowVersion you last read."
57
+ end
58
+
59
+ value
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,326 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Physical POS management: stores, registers, logical terminals with their bank rows, payment-provider
5
+ # rows and device links, devices with their identity keys, the end-of-day policy, the catalog and the
6
+ # overview (/api/v1/physical-pos). Reads need physical_pos:view, writes physical_pos:manage, device
7
+ # identity writes (key revocation, enrollment revert, activation-code revocation)
8
+ # physical_pos:identity; a TEST key can only read. Activation codes are issued in the panel only.
9
+ #
10
+ # Updates and status changes take the rowVersion you last read (409 physical_pos.version_conflict
11
+ # when the record changed). Reason codes are closed sets checked by the gateway (400
12
+ # physical_pos.input.reason_code_invalid). Routes that require an Idempotency-Key get a new UUID when
13
+ # you pass nil; a key you pass is sent exactly as given (never trimmed; '' is refused). The key sent
14
+ # comes back as idempotency_key. A key belongs to one operation: reusing it for another body or route
15
+ # is 409 physical_pos.idempotency_mismatch.
16
+ #
17
+ # Lists return a PhysicalPosPage (items, has_more, next_cursor, total_count); total_count is filled
18
+ # only with includeTotal: true on entity lists. Each list has an iterate_* twin that walks every page.
19
+ # The device identity and end-of-day policy routes are in PhysicalPosDeviceIdentity and
20
+ # PhysicalPosSettlementPolicies.
21
+ class PhysicalPosManagement
22
+ include PhysicalPosDeviceIdentity
23
+ include PhysicalPosSettlementPolicies
24
+
25
+ CREATED = ->(replayed) { replayed ? 200 : 201 }
26
+ OK = ->(_replayed) { 200 }
27
+
28
+ def initialize(gateway)
29
+ @gateway = gateway
30
+ end
31
+
32
+ # Store, register, terminal and device counts (GET /overview).
33
+ def get_overview # rubocop:disable Naming/AccessorMethodName
34
+ @gateway.record('GET', '/overview', 'overview')
35
+ end
36
+
37
+ # ── Catalog ──────────────────────────────────────────────────────────────
38
+
39
+ # Device vendors (GET /catalog/vendors).
40
+ def list_vendors
41
+ @gateway.data('GET', '/catalog/vendors')
42
+ end
43
+
44
+ # Device models; filters vendorCode, deviceType, status (GET /catalog/device-models).
45
+ def list_device_models(**filters)
46
+ @gateway.data('GET', '/catalog/device-models', query: query(filters, 'listDeviceModels'))
47
+ end
48
+
49
+ # Banks a terminal row can belong to (GET /catalog/acquirers).
50
+ def list_acquirers
51
+ @gateway.data('GET', '/catalog/acquirers')
52
+ end
53
+
54
+ # ── Stores ───────────────────────────────────────────────────────────────
55
+
56
+ def list_stores(**filters)
57
+ @gateway.page('/stores', query(filters, 'listStores'))
58
+ end
59
+
60
+ def iterate_stores(**filters, &block)
61
+ PhysicalPosResponses.each_item(filters, block) { |page| list_stores(**page) }
62
+ end
63
+
64
+ # result['store']; 201 new / 200 replay.
65
+ def create_store(request, idempotency_key: nil)
66
+ @gateway.keyed_write('/stores', body(request, 'createStore'), idempotency_key, CREATED)
67
+ end
68
+
69
+ # { 'store', 'registerSummary' => { activeCount, archivedCount }, 'assignedDeviceCount' }.
70
+ def get_store(store_id)
71
+ @gateway.data('GET', store_path(store_id))
72
+ end
73
+
74
+ # nil clears city, district, addressLine, externalRef; a field left out is unchanged.
75
+ def update_store(store_id, request)
76
+ @gateway.record('PATCH', store_path(store_id), 'store', body: body(request, 'updateStore'))
77
+ end
78
+
79
+ # { 'store', 'archivedRegisterCount' }; the active registers are archived with it.
80
+ def archive_store(store_id, request)
81
+ @gateway.data('POST', "#{store_path(store_id)}/archive", body: status_change(request))
82
+ end
83
+
84
+ def restore_store(store_id, request)
85
+ @gateway.record('POST', "#{store_path(store_id)}/restore", 'store', body: status_change(request))
86
+ end
87
+
88
+ def list_store_audit(store_id, **filters)
89
+ @gateway.page("#{store_path(store_id)}/audit", query(filters, 'history'))
90
+ end
91
+
92
+ def iterate_store_audit(store_id, **filters, &block)
93
+ PhysicalPosResponses.each_item(filters, block) { |page| list_store_audit(store_id, **page) }
94
+ end
95
+
96
+ # ── Registers ────────────────────────────────────────────────────────────
97
+
98
+ def list_registers(store_id, **filters)
99
+ @gateway.page("#{store_path(store_id)}/registers", query(filters, 'listRegisters'))
100
+ end
101
+
102
+ def iterate_registers(store_id, **filters, &block)
103
+ PhysicalPosResponses.each_item(filters, block) { |page| list_registers(store_id, **page) }
104
+ end
105
+
106
+ # result['register']; 201 new / 200 replay.
107
+ def create_register(store_id, request, idempotency_key: nil)
108
+ path = "#{store_path(store_id)}/registers"
109
+ @gateway.keyed_write(path, body(request, 'createRegister'), idempotency_key, CREATED)
110
+ end
111
+
112
+ def update_register(register_id, request)
113
+ @gateway.record('PATCH', register_path(register_id), 'register', body: body(request, 'updateRegister'))
114
+ end
115
+
116
+ def archive_register(register_id, request)
117
+ @gateway.record('POST', "#{register_path(register_id)}/archive", 'register', body: status_change(request))
118
+ end
119
+
120
+ def restore_register(register_id, request)
121
+ @gateway.record('POST', "#{register_path(register_id)}/restore", 'register', body: status_change(request))
122
+ end
123
+
124
+ def list_register_audit(register_id, **filters)
125
+ @gateway.page("#{register_path(register_id)}/audit", query(filters, 'history'))
126
+ end
127
+
128
+ def iterate_register_audit(register_id, **filters, &block)
129
+ PhysicalPosResponses.each_item(filters, block) { |page| list_register_audit(register_id, **page) }
130
+ end
131
+
132
+ # ── Logical terminals ────────────────────────────────────────────────────
133
+
134
+ def list_terminals(**filters)
135
+ @gateway.page('/terminals', query(filters, 'listTerminals'))
136
+ end
137
+
138
+ def iterate_terminals(**filters, &block)
139
+ PhysicalPosResponses.each_item(filters, block) { |page| list_terminals(**page) }
140
+ end
141
+
142
+ # result['terminal']; 201 new / 200 replay.
143
+ def create_terminal(request, idempotency_key: nil)
144
+ @gateway.keyed_write('/terminals', body(request, 'createTerminal'), idempotency_key, CREATED)
145
+ end
146
+
147
+ # { 'terminal', 'acquirers' => { items, pageInfo } }.
148
+ def get_terminal(terminal_id)
149
+ @gateway.data('GET', terminal_path(terminal_id))
150
+ end
151
+
152
+ def update_terminal(terminal_id, request)
153
+ @gateway.record('PATCH', terminal_path(terminal_id), 'terminal', body: body(request, 'updateTerminal'))
154
+ end
155
+
156
+ def close_terminal(terminal_id, request)
157
+ @gateway.record('POST', "#{terminal_path(terminal_id)}/close", 'terminal', body: status_change(request))
158
+ end
159
+
160
+ # Bank rows of a terminal; a row's id is the payment's terminalAcquirerId.
161
+ def list_terminal_acquirers(terminal_id, **filters)
162
+ @gateway.page("#{terminal_path(terminal_id)}/acquirers", query(filters, 'listTerminalAcquirers'))
163
+ end
164
+
165
+ def iterate_terminal_acquirers(terminal_id, **filters, &block)
166
+ PhysicalPosResponses.each_item(filters, block) { |page| list_terminal_acquirers(terminal_id, **page) }
167
+ end
168
+
169
+ # result['acquirer']; 201 new / 200 replay.
170
+ def add_terminal_acquirer(terminal_id, request, idempotency_key: nil)
171
+ path = "#{terminal_path(terminal_id)}/acquirers"
172
+ @gateway.keyed_write(path, body(request, 'addTerminalAcquirer'), idempotency_key, CREATED)
173
+ end
174
+
175
+ def update_terminal_acquirer(terminal_acquirer_id, request)
176
+ path = "/terminal-acquirers/#{id(terminal_acquirer_id, 'terminalAcquirerId')}"
177
+ @gateway.record('PATCH', path, 'acquirer', body: body(request, 'updateTerminalAcquirer'))
178
+ end
179
+
180
+ # Payment-provider rows of a terminal (e.g. a meal card provider's merchant / terminal / product
181
+ # code). A row's id is the payment's terminalProviderId.
182
+ def list_terminal_providers(terminal_id, **filters)
183
+ @gateway.page("#{terminal_path(terminal_id)}/providers", query(filters, 'listTerminalProviders'))
184
+ end
185
+
186
+ def iterate_terminal_providers(terminal_id, **filters, &block)
187
+ PhysicalPosResponses.each_item(filters, block) { |page| list_terminal_providers(terminal_id, **page) }
188
+ end
189
+
190
+ # Adds a provider row: { vendorAccountId, merchantCode, terminalCode, productCode?, label? }; the
191
+ # provider comes from the vendor account. result['provider']; 201 new / 200 replay.
192
+ def add_terminal_provider(terminal_id, request, idempotency_key: nil)
193
+ path = "#{terminal_path(terminal_id)}/providers"
194
+ @gateway.keyed_write(path, body(request, 'addTerminalProvider'), idempotency_key, CREATED)
195
+ end
196
+
197
+ # { rowVersion, label?, status? }; nil label clears it, status ACTIVE or DISABLED.
198
+ def update_terminal_provider(terminal_provider_id, request)
199
+ path = "/terminal-providers/#{id(terminal_provider_id, 'terminalProviderId')}"
200
+ @gateway.record('PATCH', path, 'provider', body: body(request, 'updateTerminalProvider'))
201
+ end
202
+
203
+ # Links the terminal to a device (closing the previous link): { 'terminal', 'link' }.
204
+ def change_terminal_device(terminal_id, request)
205
+ @gateway.data('POST', "#{terminal_path(terminal_id)}/device-link", body: body(request, 'changeTerminalDevice'))
206
+ end
207
+
208
+ # result['terminal'] and result['link'] (the closed link or nil).
209
+ def close_terminal_device_link(terminal_id, request, idempotency_key: nil)
210
+ @gateway.keyed_write("#{terminal_path(terminal_id)}/device-link/close", status_change(request), idempotency_key, OK)
211
+ end
212
+
213
+ def list_terminal_links(terminal_id, **filters)
214
+ @gateway.page("#{terminal_path(terminal_id)}/links", query(filters, 'history'))
215
+ end
216
+
217
+ def iterate_terminal_links(terminal_id, **filters, &block)
218
+ PhysicalPosResponses.each_item(filters, block) { |page| list_terminal_links(terminal_id, **page) }
219
+ end
220
+
221
+ def list_terminal_audit(terminal_id, **filters)
222
+ @gateway.page("#{terminal_path(terminal_id)}/audit", query(filters, 'history'))
223
+ end
224
+
225
+ def iterate_terminal_audit(terminal_id, **filters, &block)
226
+ PhysicalPosResponses.each_item(filters, block) { |page| list_terminal_audit(terminal_id, **page) }
227
+ end
228
+
229
+ # ── Devices ──────────────────────────────────────────────────────────────
230
+
231
+ def list_devices(**filters)
232
+ @gateway.page('/devices', query(filters, 'listDevices'))
233
+ end
234
+
235
+ def iterate_devices(**filters, &block)
236
+ PhysicalPosResponses.each_item(filters, block) { |page| list_devices(**page) }
237
+ end
238
+
239
+ # result['device']; 201 new / 200 replay.
240
+ def create_device(request, idempotency_key: nil)
241
+ @gateway.keyed_write('/devices', body(request, 'createDevice'), idempotency_key, CREATED)
242
+ end
243
+
244
+ def get_device(device_id)
245
+ @gateway.record('GET', device_path(device_id), 'device')
246
+ end
247
+
248
+ def update_device(device_id, request)
249
+ @gateway.record('PATCH', device_path(device_id), 'device', body: body(request, 'updateDevice'))
250
+ end
251
+
252
+ # Assigns the device to a store (and register): { 'device', 'assignment', 'previousAssignmentId' }.
253
+ def assign_device(device_id, request)
254
+ @gateway.data('POST', "#{device_path(device_id)}/assignment", body: body(request, 'assignDevice'))
255
+ end
256
+
257
+ # Moves the device to storage: result['device'] and result['closedAssignment'].
258
+ def close_device_assignment(device_id, request, idempotency_key: nil)
259
+ @gateway.keyed_write("#{device_path(device_id)}/assignment/close", status_change(request), idempotency_key, OK)
260
+ end
261
+
262
+ # target: ACTIVE, SUSPENDED or MAINTENANCE.
263
+ def change_device_lifecycle(device_id, request)
264
+ @gateway.record('POST', "#{device_path(device_id)}/lifecycle", 'device', body: body(request, 'changeDeviceLifecycle'))
265
+ end
266
+
267
+ # result['device']. Retirement is final.
268
+ def retire_device(device_id, request, idempotency_key: nil)
269
+ @gateway.keyed_write("#{device_path(device_id)}/retire", status_change(request), idempotency_key, OK)
270
+ end
271
+
272
+ def list_device_assignments(device_id, **filters)
273
+ @gateway.page("#{device_path(device_id)}/assignments", query(filters, 'history'))
274
+ end
275
+
276
+ def iterate_device_assignments(device_id, **filters, &block)
277
+ PhysicalPosResponses.each_item(filters, block) { |page| list_device_assignments(device_id, **page) }
278
+ end
279
+
280
+ def list_device_audit(device_id, **filters)
281
+ @gateway.page("#{device_path(device_id)}/audit", query(filters, 'history'))
282
+ end
283
+
284
+ def iterate_device_audit(device_id, **filters, &block)
285
+ PhysicalPosResponses.each_item(filters, block) { |page| list_device_audit(device_id, **page) }
286
+ end
287
+
288
+ def inspect
289
+ '#<Lunixi::PhysicalPosManagement>'
290
+ end
291
+
292
+ private
293
+
294
+ def body(request, operation)
295
+ PhysicalPosRequest.body!(request, PHYSICAL_POS_REQUEST_FIELDS.fetch(operation), "#{operation} request")
296
+ end
297
+
298
+ def status_change(request)
299
+ body(request, 'statusChange')
300
+ end
301
+
302
+ def query(filters, route)
303
+ PhysicalPosFilters.query!(filters, route)
304
+ end
305
+
306
+ def id(value, field)
307
+ PhysicalPosIdentifiers.path_id(value, field)
308
+ end
309
+
310
+ def store_path(store_id)
311
+ "/stores/#{id(store_id, 'storeId')}"
312
+ end
313
+
314
+ def register_path(register_id)
315
+ "/registers/#{id(register_id, 'registerId')}"
316
+ end
317
+
318
+ def terminal_path(terminal_id)
319
+ "/terminals/#{id(terminal_id, 'terminalId')}"
320
+ end
321
+
322
+ def device_path(device_id)
323
+ "/devices/#{id(device_id, 'deviceId')}"
324
+ end
325
+ end
326
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Declared physical POS money in responses and webhooks: canonical minor-unit strings ("4500").
5
+ # Counts, rates and opaque metadata stay untouched; net* fields and everything under difference may be
6
+ # negative.
7
+ module PhysicalPosMoney
8
+ FIELDS = %w[
9
+ amountFromMinor amountMinor amountToMinor approvedAmountMinor baseMinor capturedMinor lineTotalMinor netBaseMinor
10
+ netMinor netTaxMinor refundBaseMinor refundMinor refundTaxMinor refundedAmountMinor refundedMinor reservedAmountMinor
11
+ reservedMinor reversalReservedMinor reversedMinor saleBaseMinor saleMinor saleTaxMinor unitAmountMinor unitPriceMinor
12
+ voidBaseMinor voidMinor voidTaxMinor
13
+ ].freeze
14
+ CONTAINERS = %w[
15
+ data payment payments items refundItems taxes rows transaction transactions root children itemSummary amountTotals
16
+ reported system difference totals lines
17
+ ].freeze
18
+ NULLABLE = %w[approvedAmountMinor unitAmountMinor].freeze
19
+
20
+ module_function
21
+
22
+ def validate(value, difference: false)
23
+ case value
24
+ when Array then value.each { |entry| validate(entry, difference: difference) }
25
+ when Hash
26
+ value.each do |name, entry|
27
+ key = name.to_s
28
+ if FIELDS.include?(key)
29
+ next if entry.nil? && NULLABLE.include?(key)
30
+
31
+ amount!(entry, key, difference || key.start_with?('net'))
32
+ elsif CONTAINERS.include?(key)
33
+ validate(entry, difference: difference || key == 'difference')
34
+ end
35
+ end
36
+ end
37
+ value
38
+ end
39
+
40
+ def amount!(value, key, signed)
41
+ Money.minor(value, positive: false, signed: signed)
42
+ rescue ConfigurationError
43
+ raise ConfigurationError, "The physical POS answer carries a non-canonical amount in '#{key}' (minor-unit string expected)", cause: nil
44
+ end
45
+ end
46
+ end