lunixi-sdk 1.2.2 → 2.0.2

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 (72) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +62 -0
  3. data/README.md +278 -10
  4. data/README.tr.md +282 -8
  5. data/docs/ruby.en.md +11 -1
  6. data/docs/ruby.tr.md +11 -1
  7. data/lib/lunixi/bank_connect.rb +340 -0
  8. data/lib/lunixi/bank_connect_filters.rb +114 -0
  9. data/lib/lunixi/bank_connect_values.rb +205 -0
  10. data/lib/lunixi/bank_transfer.rb +106 -0
  11. data/lib/lunixi/card_requests.rb +171 -0
  12. data/lib/lunixi/client.rb +57 -16
  13. data/lib/lunixi/direct_method_payment_request.rb +245 -0
  14. data/lib/lunixi/enabled_installments.rb +28 -0
  15. data/lib/lunixi/errors.rb +69 -3
  16. data/lib/lunixi/fraud.rb +81 -5
  17. data/lib/lunixi/identity.rb +94 -0
  18. data/lib/lunixi/identity_values.rb +28 -0
  19. data/lib/lunixi/insurance.rb +294 -0
  20. data/lib/lunixi/insurance_request.rb +134 -0
  21. data/lib/lunixi/insurance_values.rb +200 -0
  22. data/lib/lunixi/kyc.rb +189 -0
  23. data/lib/lunixi/kyc_values.rb +158 -0
  24. data/lib/lunixi/marketplace.rb +268 -0
  25. data/lib/lunixi/marketplace_values.rb +86 -0
  26. data/lib/lunixi/method_fields.rb +142 -0
  27. data/lib/lunixi/money.rb +7 -4
  28. data/lib/lunixi/order_details.rb +115 -0
  29. data/lib/lunixi/payment_link_filters.rb +32 -0
  30. data/lib/lunixi/payment_link_image_rules.rb +85 -0
  31. data/lib/lunixi/payment_link_rules.rb +132 -0
  32. data/lib/lunixi/payment_link_values.rb +136 -0
  33. data/lib/lunixi/payment_links.rb +152 -0
  34. data/lib/lunixi/payment_values.rb +86 -0
  35. data/lib/lunixi/payments.rb +170 -8
  36. data/lib/lunixi/physical_pos.rb +183 -0
  37. data/lib/lunixi/physical_pos_card_data.rb +117 -0
  38. data/lib/lunixi/physical_pos_card_number.rb +65 -0
  39. data/lib/lunixi/physical_pos_device_identity.rb +44 -0
  40. data/lib/lunixi/physical_pos_filters.rb +58 -0
  41. data/lib/lunixi/physical_pos_gateway.rb +153 -0
  42. data/lib/lunixi/physical_pos_identifiers.rb +62 -0
  43. data/lib/lunixi/physical_pos_management.rb +326 -0
  44. data/lib/lunixi/physical_pos_money.rb +46 -0
  45. data/lib/lunixi/physical_pos_request.rb +126 -0
  46. data/lib/lunixi/physical_pos_responses.rb +102 -0
  47. data/lib/lunixi/physical_pos_results.rb +52 -0
  48. data/lib/lunixi/physical_pos_settlement_policies.rb +71 -0
  49. data/lib/lunixi/physical_pos_value.rb +43 -0
  50. data/lib/lunixi/physical_pos_values.rb +203 -0
  51. data/lib/lunixi/physical_pos_webhook.rb +147 -0
  52. data/lib/lunixi/product_webhooks.rb +106 -0
  53. data/lib/lunixi/promissory_note.rb +155 -0
  54. data/lib/lunixi/reference.rb +41 -0
  55. data/lib/lunixi/route_request.rb +121 -0
  56. data/lib/lunixi/route_response.rb +101 -0
  57. data/lib/lunixi/route_table.rb +128 -0
  58. data/lib/lunixi/route_value.rb +60 -0
  59. data/lib/lunixi/sanction.rb +244 -0
  60. data/lib/lunixi/sanction_values.rb +132 -0
  61. data/lib/lunixi/split_payment.rb +150 -0
  62. data/lib/lunixi/subscription_resources.rb +357 -0
  63. data/lib/lunixi/subscription_values.rb +233 -0
  64. data/lib/lunixi/subscriptions.rb +202 -0
  65. data/lib/lunixi/version.rb +1 -1
  66. data/lib/lunixi/wallet.rb +153 -0
  67. data/lib/lunixi/wallet_resources.rb +407 -0
  68. data/lib/lunixi/wallet_routes.rb +126 -0
  69. data/lib/lunixi/wallet_values.rb +71 -0
  70. data/lib/lunixi/wire_money.rb +67 -0
  71. data/lib/lunixi.rb +58 -0
  72. metadata +59 -1
@@ -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
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Local checks shared by PhysicalPos and PhysicalPosManagement: field lists and value kinds. Single
5
+ # values are checked by PhysicalPosValue, card data is refused by PhysicalPosCardData, the
6
+ # Idempotency-Key and path identifiers are checked by PhysicalPosIdentifiers and filters by
7
+ # PhysicalPosFilters; answers and errors are read by PhysicalPosResponses.
8
+ # Shape and canonical money are checked here; value rules (operation set, ranges, item totals, target
9
+ # uniqueness) stay on the gateway, which answers with a typed physical_pos.* code.
10
+ module PhysicalPosRequest
11
+ BASE = '/api/v1/physical-pos'
12
+ ROUTE = %r{\A/api/v1/physical-pos(?:[/?]|\z)}
13
+ # A field check's answer for "leave the field out" (nil is a real value: an explicit clear).
14
+ OMIT = Object.new.freeze
15
+ SALE_ITEM_KINDS = {
16
+ 'lineNo' => 'int*', 'name' => 'string*', 'quantityMilli' => 'int*', 'unitCode' => 'string*', 'unitPriceMinor' => 'money*',
17
+ 'taxGroupCode' => 'string*', 'lineTotalMinor' => 'money*', 'barcode' => 'string'
18
+ }.freeze
19
+ REFUND_ITEM_KINDS = { 'lineNo' => 'int*', 'quantityMilli' => 'int*', 'amountMinor' => 'money' }.freeze
20
+ TARGET_KINDS = PHYSICAL_POS_PAYMENT_TARGET_FIELDS.to_h { |name| [name, 'string'] }.freeze
21
+
22
+ module_function
23
+
24
+ # ── Bodies ───────────────────────────────────────────────────────────────
25
+
26
+ # Builds a request body from a field list (PHYSICAL_POS_REQUEST_FIELDS): card-data keys first
27
+ # (PhysicalPosCardDataRejectedError), then unknown fields, required fields and value types
28
+ # (ConfigurationError), then card-number values in the scanned free-text fields. Keys are the wire
29
+ # names (String or Symbol); snake_case names are accepted too. Nothing is sent when a check fails.
30
+ def body!(request, kinds, label)
31
+ PhysicalPosCardData.reject_card_data!(request, '(body)') unless request.nil?
32
+ given = wire_keys!(request, kinds.keys, label)
33
+ body = {}
34
+ kinds.each do |key, kind|
35
+ unless given.key?(key)
36
+ raise ConfigurationError, "'#{key}' is required." if kind.end_with?('*')
37
+
38
+ next
39
+ end
40
+ checked = check_value(kind, given[key], key)
41
+ body[key] = checked unless checked.equal?(OMIT)
42
+ end
43
+ PhysicalPosCardData.reject_card_numbers!(body)
44
+ body
45
+ end
46
+
47
+ # One value against its kind. Money is a canonical string; present nil or blank money is refused.
48
+ # nil is sent only for a nullable (?) field and left out for any other optional field; '' is left
49
+ # out for an optional string and refused for a required one.
50
+ def check_value(kind_spec, value, field)
51
+ required = kind_spec.end_with?('*')
52
+ nullable = kind_spec.end_with?('?')
53
+ kind = kind_spec.delete_suffix('*').delete_suffix('?')
54
+ return PhysicalPosValue.money!(value, field) if kind == 'money'
55
+ return nil_value(required, nullable, field) if value.nil?
56
+ return OMIT if value == '' && !required
57
+
58
+ case kind
59
+ when 'string' then PhysicalPosValue.string!(value, field)
60
+ when 'int' then PhysicalPosValue.integer!(value, field)
61
+ when 'rowVersion' then PhysicalPosIdentifiers.row_version!(value, field)
62
+ when 'bool' then PhysicalPosValue.boolean!(value, field)
63
+ when 'strings' then PhysicalPosValue.strings!(value, field)
64
+ when 'target' then object_of(value, TARGET_KINDS, field)
65
+ when 'saleItems' then items_of(value, SALE_ITEM_KINDS, field)
66
+ when 'refundItems' then items_of(value, REFUND_ITEM_KINDS, field)
67
+ else raise ConfigurationError, "Unsupported field kind '#{kind_spec}'."
68
+ end
69
+ end
70
+
71
+ def nil_value(required, nullable, field)
72
+ return nil if nullable
73
+ raise ConfigurationError, "'#{field}' is required." if required
74
+
75
+ OMIT
76
+ end
77
+
78
+ def object_of(value, kinds, field)
79
+ given = wire_keys!(value, kinds.keys, "'#{field}'")
80
+ kinds.each_with_object({}) do |(key, kind), out|
81
+ next unless given.key?(key)
82
+
83
+ checked = check_value(kind, given[key], "#{field}.#{key}")
84
+ out[key] = checked unless checked.equal?(OMIT)
85
+ end
86
+ end
87
+
88
+ def items_of(value, kinds, field)
89
+ unless value.is_a?(Array) && !value.empty?
90
+ raise ConfigurationError, "'#{field}' must be a non-empty array; leave the field out for a request without items."
91
+ end
92
+
93
+ value.each_with_index.map do |item, index|
94
+ path = "#{field}[#{index}]"
95
+ out = object_of(item, kinds, path)
96
+ kinds.each { |key, kind| raise ConfigurationError, "'#{path}.#{key}' is required." if kind.end_with?('*') && !out.key?(key) }
97
+ out
98
+ end
99
+ end
100
+
101
+ # Wire names of a body or filter set: String or Symbol keys, the wire name or its snake_case form.
102
+ def wire_keys!(value, allowed, label, kind = 'field')
103
+ raise ConfigurationError, "#{label} must be a Hash." unless value.is_a?(Hash)
104
+
105
+ unknown = []
106
+ given = value.each_with_object({}) do |(key, entry), out|
107
+ raise ConfigurationError, "#{label} keys must be strings or symbols." unless key.is_a?(String) || key.is_a?(Symbol)
108
+
109
+ name = key.to_s
110
+ wire = allowed.include?(name) ? name : camel(name)
111
+ next unknown << name unless allowed.include?(wire)
112
+ raise ConfigurationError, "#{label} #{kind} '#{wire}' is given twice." if out.key?(wire)
113
+
114
+ out[wire] = entry
115
+ end
116
+ return given if unknown.empty?
117
+
118
+ raise ConfigurationError, "Unknown #{label} #{kind}(s): #{unknown.join(', ')}. Allowed: #{allowed.join(', ')}. " \
119
+ 'The gateway rejects unknown fields with 400.'
120
+ end
121
+
122
+ def camel(name)
123
+ name.gsub(/_([a-z0-9])/) { Regexp.last_match(1).upcase }
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Reads physical POS answers (records, pages, keyed write results) and maps gateway errors to the
5
+ # typed physical POS errors.
6
+ module PhysicalPosResponses
7
+ module_function
8
+
9
+ def unwrap(response)
10
+ response.is_a?(Hash) && response.key?('data') ? response['data'] : response
11
+ end
12
+
13
+ # data[name] of a single-record answer, or data itself when the wrapper is missing.
14
+ def member(response, name)
15
+ data = unwrap(response)
16
+ data.is_a?(Hash) && !data[name].nil? ? data[name] : data
17
+ end
18
+
19
+ # Paging from the envelope's top-level pageInfo.
20
+ def page(response)
21
+ payload = unwrap(response)
22
+ items = payload.is_a?(Hash) && payload['items'].is_a?(Array) ? payload['items'] : []
23
+ info = hash_at(response, 'pageInfo') || hash_at(payload, 'pageInfo') || {}
24
+ cursor = info['nextCursor'].is_a?(String) && !info['nextCursor'].empty? ? info['nextCursor'] : nil
25
+ total = info['totalCount'].is_a?(Integer) ? info['totalCount'] : nil
26
+ PhysicalPosPage.new(items: items, has_more: info['hasMore'] == true && !cursor.nil?, next_cursor: cursor, total_count: total)
27
+ end
28
+
29
+ def hash_at(value, key)
30
+ value[key] if value.is_a?(Hash) && value[key].is_a?(Hash)
31
+ end
32
+
33
+ # Every item of every page, fetching the next page only when it is needed. Without a block it
34
+ # returns an Enumerator.
35
+ def each_item(filters, block, &fetch)
36
+ items = Enumerator.new do |yielder|
37
+ query = filters.transform_keys(&:to_sym)
38
+ loop do
39
+ page = fetch.call(query)
40
+ page.items.each { |item| yielder << item }
41
+ break unless page.has_more && page.next_cursor
42
+
43
+ query = query.merge(cursor: page.next_cursor)
44
+ end
45
+ end
46
+ return items unless block
47
+
48
+ items.each(&block)
49
+ nil
50
+ end
51
+
52
+ # Keyed write answer: the route's data plus replayed, the status code and the key sent.
53
+ def write_result(response, key, fallback)
54
+ data = unwrap(response)
55
+ data = {} unless data.is_a?(Hash)
56
+ replayed = data['replayed'] == true
57
+ PhysicalPosWriteResult.new(data: data, replayed: replayed, status_code: status_code(response, fallback.call(replayed)), idempotency_key: key)
58
+ end
59
+
60
+ def status_code(response, fallback)
61
+ value = response.is_a?(Hash) ? response['statusCode'] : nil
62
+ value.is_a?(Integer) && value.between?(200, 299) ? value : fallback
63
+ end
64
+
65
+ # Typed physical POS errors for one answered request: card data (field path), void after
66
+ # end-of-day (allowed_operation), 429 (retry_after in seconds). The key of a write is attached.
67
+ def translate(error, key = nil)
68
+ return error unless error.is_a?(ApiError)
69
+
70
+ common = { status: error.status, code: error.code, request_id: error.request_id, details: error.details,
71
+ idempotency_key: key || error.idempotency_key, message: error.message }
72
+ if error.code == PhysicalPosCardDataRejectedError::CODE
73
+ field = error.details['field']
74
+ PhysicalPosCardDataRejectedError.new(field: field.is_a?(String) ? field : nil, retry_after: error.retry_after, **common)
75
+ elsif error.code == PhysicalPosVoidAfterSettlementError::CODE
76
+ allowed = error.details['allowedOperation']
77
+ PhysicalPosVoidAfterSettlementError.new(allowed_operation: allowed.is_a?(String) ? allowed : nil, retry_after: error.retry_after, **common)
78
+ elsif error.status == 429
79
+ PhysicalPosRateLimitError.new(retry_after: retry_after_seconds(error), **common)
80
+ elsif key.nil?
81
+ error
82
+ else
83
+ error.class.new(retry_after: error.retry_after, **common)
84
+ end
85
+ end
86
+
87
+ # The Retry-After header in seconds, or details.retryAfterSeconds when the header is missing.
88
+ def retry_after_seconds(error)
89
+ number(error.retry_after) || number(error.details['retryAfterSeconds'])
90
+ end
91
+
92
+ def number(value)
93
+ return value if value.is_a?(Integer) || (value.is_a?(Float) && value.finite?)
94
+ return nil unless value.is_a?(String)
95
+
96
+ text = value.strip
97
+ return text.to_i if text.match?(/\A\d{1,9}\z/)
98
+
99
+ text.match?(/\A\d{1,9}\.\d{1,9}\z/) ? text.to_f : nil
100
+ end
101
+ end
102
+ end