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,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # One page of a physical POS list. total_count is filled only with includeTotal: true on entity
5
+ # lists; pass next_cursor as cursor: for the next page (or use the iterate_* methods).
6
+ PhysicalPosPage = Struct.new(:items, :has_more, :next_cursor, :total_count, keyword_init: true)
7
+
8
+ # Answer of a physical POS write that carries an Idempotency-Key.
9
+ #
10
+ # data is the route's payload unchanged ({ 'payment' => … }, { 'store' => … },
11
+ # { 'device' => …, 'closedAssignment' => … }, { 'run' => … }); result['store'] reads it directly.
12
+ # replayed is true when the same key and body were sent before: the record is then its CURRENT state.
13
+ # status_code is 202 for a new payment, reversal or end-of-day run (accepted, not paid: follow the
14
+ # outcome by webhook or get_payment), 201 for a created record, 200 for a replay, a cancel or a state
15
+ # change. idempotency_key is the key sent; keep it with your order, an uncertain retry must reuse it.
16
+ class PhysicalPosWriteResult
17
+ attr_reader :data, :replayed, :status_code, :idempotency_key
18
+
19
+ def initialize(data:, replayed:, status_code:, idempotency_key:)
20
+ @data = data
21
+ @replayed = replayed
22
+ @status_code = status_code
23
+ @idempotency_key = idempotency_key
24
+ end
25
+
26
+ def [](name)
27
+ data[name.to_s]
28
+ end
29
+
30
+ # The payment of a payment write (for a reversal, the new child payment).
31
+ def payment
32
+ data['payment']
33
+ end
34
+
35
+ def replayed?
36
+ replayed
37
+ end
38
+
39
+ # True for a newly accepted payment, reversal or end-of-day run (HTTP 202).
40
+ def accepted?
41
+ status_code == 202
42
+ end
43
+
44
+ def to_h
45
+ data.merge('replayed' => replayed, 'statusCode' => status_code, 'idempotencyKey' => idempotency_key)
46
+ end
47
+
48
+ def inspect
49
+ "#<Lunixi::PhysicalPosWriteResult status_code=#{status_code} replayed=#{replayed}>"
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # End-of-day policy routes of PhysicalPosManagement (account → store → device). Mixed into
5
+ # PhysicalPosManagement; uses its request and path helpers.
6
+ #
7
+ # A level's policy replaces the level above it entirely. set_* sends the full setting: { mode
8
+ # (MANUAL | SCHEDULED | DEVICE_AUTO), scheduleTime?, timeZone?, scheduleDays?, retryWindowMinutes?,
9
+ # retryIntervalMinutes?, offlineBehavior?, overdueAlertHours?, expectedRowVersion? }. clear_* resets
10
+ # the account to MANUAL, or removes a store / device override (it then inherits).
11
+ # expectedRowVersion is the policy's rowVersion you read (409 physical_pos.version_conflict when it
12
+ # changed); leave it out for last write wins. Each call returns the policy.
13
+ module PhysicalPosSettlementPolicies
14
+ def get_account_settlement_policy # rubocop:disable Naming/AccessorMethodName
15
+ @gateway.record('GET', '/settlement-policy', 'policy')
16
+ end
17
+
18
+ def set_account_settlement_policy(request) # rubocop:disable Naming/AccessorMethodName
19
+ @gateway.record('PUT', '/settlement-policy', 'policy', body: settlement_policy(request))
20
+ end
21
+
22
+ def clear_account_settlement_policy(expected_row_version = nil)
23
+ @gateway.record('DELETE', '/settlement-policy', 'policy', query: expected_row_version_query(expected_row_version))
24
+ end
25
+
26
+ def get_store_settlement_policy(store_id)
27
+ @gateway.record('GET', "#{store_path(store_id)}/settlement-policy", 'policy')
28
+ end
29
+
30
+ def set_store_settlement_policy(store_id, request)
31
+ @gateway.record('PUT', "#{store_path(store_id)}/settlement-policy", 'policy', body: settlement_policy(request))
32
+ end
33
+
34
+ def clear_store_settlement_policy(store_id, expected_row_version = nil)
35
+ @gateway.record('DELETE', "#{store_path(store_id)}/settlement-policy", 'policy', query: expected_row_version_query(expected_row_version))
36
+ end
37
+
38
+ def get_device_settlement_policy(device_id)
39
+ @gateway.record('GET', "#{device_path(device_id)}/settlement-policy", 'policy')
40
+ end
41
+
42
+ # DEVICE_AUTO only on devices that report their end-of-day results.
43
+ def set_device_settlement_policy(device_id, request)
44
+ @gateway.record('PUT', "#{device_path(device_id)}/settlement-policy", 'policy', body: settlement_policy(request))
45
+ end
46
+
47
+ def clear_device_settlement_policy(device_id, expected_row_version = nil)
48
+ @gateway.record('DELETE', "#{device_path(device_id)}/settlement-policy", 'policy', query: expected_row_version_query(expected_row_version))
49
+ end
50
+
51
+ # The policy a device follows (GET /devices/{deviceId}/settlement-policy/effective): { deviceId,
52
+ # sourceScopeType (ACCOUNT | STORE | DEVICE), policy, serverSettlementSupported, deviceAutoSupported,
53
+ # nextScheduledAt, lastSettlementAt, overdue, scheduleWarning }.
54
+ def get_effective_settlement_policy(device_id)
55
+ @gateway.record('GET', "#{device_path(device_id)}/settlement-policy/effective", 'effective')
56
+ end
57
+
58
+ private
59
+
60
+ def settlement_policy(request)
61
+ body(request, 'setSettlementPolicy')
62
+ end
63
+
64
+ # DELETE …/settlement-policy?expectedRowVersion= (left out when nil).
65
+ def expected_row_version_query(expected_row_version)
66
+ return {} if expected_row_version.nil?
67
+
68
+ { 'expectedRowVersion' => PhysicalPosIdentifiers.row_version!(expected_row_version, 'expectedRowVersion').to_s }
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Single values of the physical POS bodies and filters: strings, JSON integers, booleans, string lists
5
+ # and canonical minor-unit money. The error names the field, never its value. Not a public API.
6
+ module PhysicalPosValue
7
+ MAX_SAFE_INTEGER = JsonBody::MAX_SAFE_INTEGER
8
+
9
+ module_function
10
+
11
+ def string!(value, field)
12
+ raise ConfigurationError, "'#{field}' must be a non-empty string." unless value.is_a?(String) && !value.empty?
13
+
14
+ value
15
+ end
16
+
17
+ def integer!(value, field)
18
+ raise ConfigurationError, "'#{field}' must be an integer (a JSON number, not a string)." unless value.is_a?(Integer) && value.abs <= MAX_SAFE_INTEGER
19
+
20
+ value
21
+ end
22
+
23
+ def boolean!(value, field)
24
+ raise ConfigurationError, "'#{field}' must be a boolean." unless [true, false].include?(value)
25
+
26
+ value
27
+ end
28
+
29
+ def strings!(value, field)
30
+ unless value.is_a?(Array) && value.all? { |entry| entry.is_a?(String) && !entry.empty? }
31
+ raise ConfigurationError, "'#{field}' must be an array of non-empty strings."
32
+ end
33
+
34
+ value.dup
35
+ end
36
+
37
+ def money!(value, field)
38
+ Money.minor(value, positive: true)
39
+ rescue ConfigurationError
40
+ raise ConfigurationError, "'#{field}' must be a canonical minor-unit string such as \"4500\" (not a number).", cause: nil
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # Physical POS values, request fields and filters (/api/v1/physical-pos).
5
+ #
6
+ # Statuses and operations are open sets on the wire: the SDK lists the values the gateway sends today
7
+ # and never rejects one it does not know. The field and filter lists are closed: the gateway rejects
8
+ # an unknown body field or query parameter with 400, so the SDK checks them before sending.
9
+ module PhysicalPosPaymentOperation
10
+ SALE = 'SALE'
11
+ PREAUTH_OPEN = 'PREAUTH_OPEN'
12
+ REFUND_UNMATCHED = 'REFUND_UNMATCHED'
13
+ VOID = 'VOID'
14
+ REFUND = 'REFUND'
15
+ PREAUTH_CLOSE = 'PREAUTH_CLOSE'
16
+ PREAUTH_CANCEL = 'PREAUTH_CANCEL'
17
+
18
+ # Operations that start a root payment (create_payment).
19
+ ROOT = [SALE, PREAUTH_OPEN, REFUND_UNMATCHED].freeze
20
+ # Operations of a reversal (create_reversal).
21
+ REVERSAL = [VOID, REFUND, PREAUTH_CLOSE, PREAUTH_CANCEL].freeze
22
+ ALL = (ROOT + REVERSAL).freeze
23
+ end
24
+
25
+ module PhysicalPosPaymentStatus
26
+ NOT_STARTED = 'NOT_STARTED'
27
+ IN_PROGRESS = 'IN_PROGRESS'
28
+ APPROVED = 'APPROVED'
29
+ PARTIALLY_APPROVED = 'PARTIALLY_APPROVED'
30
+ DECLINED = 'DECLINED'
31
+ CANCELLED = 'CANCELLED'
32
+ EXPIRED = 'EXPIRED'
33
+ FAILED = 'FAILED'
34
+ UNKNOWN = 'UNKNOWN'
35
+ MANUAL_REVIEW = 'MANUAL_REVIEW'
36
+
37
+ ALL = [NOT_STARTED, IN_PROGRESS, APPROVED, PARTIALLY_APPROVED, DECLINED, CANCELLED, EXPIRED, FAILED, UNKNOWN, MANUAL_REVIEW].freeze
38
+ FINAL_STATUSES = [APPROVED, PARTIALLY_APPROVED, DECLINED, CANCELLED, EXPIRED, FAILED].freeze
39
+ end
40
+
41
+ module PhysicalPosReversalStatus
42
+ NONE = 'NONE'
43
+ PARTIALLY_REFUNDED = 'PARTIALLY_REFUNDED'
44
+ REFUNDED = 'REFUNDED'
45
+ VOIDED = 'VOIDED'
46
+ PREAUTH_CLOSED = 'PREAUTH_CLOSED'
47
+ PREAUTH_CANCELLED = 'PREAUTH_CANCELLED'
48
+ PREAUTH_EXPIRED = 'PREAUTH_EXPIRED'
49
+
50
+ ALL = [NONE, PARTIALLY_REFUNDED, REFUNDED, VOIDED, PREAUTH_CLOSED, PREAUTH_CANCELLED, PREAUTH_EXPIRED].freeze
51
+ end
52
+
53
+ # Webhook event types. physical_pos.payment.created and .in_progress are internal and never delivered.
54
+ # Reversals (void, refund, pre-authorisation close / cancel) use the same payment events; tell them
55
+ # apart with data.operation and data.rootPaymentId, and the original payment's source with
56
+ # data.original.origin.
57
+ #
58
+ # PAYMENT_DEVICE_SALE reports a sale made directly on the device (origin: DEVICE_DIRECT): it arrives
59
+ # approved, with deviceOccurredAt; no approved event is sent for it. Its refund comes with the usual
60
+ # payment events (data.original.origin: DEVICE_DIRECT).
61
+ #
62
+ # End-of-day events (physical_pos.settlement.*) have their own payloads: completed (the device's
63
+ # result with its bank lines; any source), failed (a scheduled run could not finish in its window),
64
+ # skipped (a scheduled run was skipped for a reason you can fix) and overdue (no result within the
65
+ # policy's threshold). They carry no historySeq; deduplicate them by the event id.
66
+ module PhysicalPosEvents
67
+ PAYMENT_APPROVED = 'physical_pos.payment.approved'
68
+ PAYMENT_PARTIALLY_APPROVED = 'physical_pos.payment.partially_approved'
69
+ PAYMENT_DECLINED = 'physical_pos.payment.declined'
70
+ PAYMENT_CANCELLED = 'physical_pos.payment.cancelled'
71
+ PAYMENT_EXPIRED = 'physical_pos.payment.expired'
72
+ PAYMENT_FAILED = 'physical_pos.payment.failed'
73
+ PAYMENT_UNKNOWN = 'physical_pos.payment.unknown'
74
+ PAYMENT_MANUAL_REVIEW = 'physical_pos.payment.manual_review'
75
+ PAYMENT_DEVICE_SALE = 'physical_pos.payment.device_sale'
76
+ FISCAL_DOCUMENT_ISSUED = 'physical_pos.fiscal_document.issued'
77
+ FISCAL_DOCUMENT_FAILED = 'physical_pos.fiscal_document.failed'
78
+ FISCAL_DOCUMENT_CANCELLED = 'physical_pos.fiscal_document.cancelled'
79
+ FISCAL_DOCUMENT_ACTION_REQUIRED = 'physical_pos.fiscal_document.action_required'
80
+ SETTLEMENT_COMPLETED = 'physical_pos.settlement.completed'
81
+ SETTLEMENT_FAILED = 'physical_pos.settlement.failed'
82
+ SETTLEMENT_OVERDUE = 'physical_pos.settlement.overdue'
83
+ SETTLEMENT_SKIPPED = 'physical_pos.settlement.skipped'
84
+ # Subscription pattern for every physical POS event.
85
+ ALL_EVENTS = 'physical_pos.*'
86
+
87
+ PAYMENT_EVENTS = [PAYMENT_APPROVED, PAYMENT_PARTIALLY_APPROVED, PAYMENT_DECLINED, PAYMENT_CANCELLED, PAYMENT_EXPIRED,
88
+ PAYMENT_FAILED, PAYMENT_UNKNOWN, PAYMENT_MANUAL_REVIEW, PAYMENT_DEVICE_SALE].freeze
89
+ FISCAL_DOCUMENT_EVENTS = [FISCAL_DOCUMENT_ISSUED, FISCAL_DOCUMENT_FAILED, FISCAL_DOCUMENT_CANCELLED, FISCAL_DOCUMENT_ACTION_REQUIRED].freeze
90
+ SETTLEMENT_EVENTS = [SETTLEMENT_COMPLETED, SETTLEMENT_FAILED, SETTLEMENT_OVERDUE, SETTLEMENT_SKIPPED].freeze
91
+ ALL = (PAYMENT_EVENTS + FISCAL_DOCUMENT_EVENTS + SETTLEMENT_EVENTS).freeze
92
+ end
93
+
94
+ PHYSICAL_POS_EVENT_PATTERN = PhysicalPosEvents::ALL_EVENTS
95
+ PHYSICAL_POS_EVENT_TYPES = PhysicalPosEvents::ALL
96
+
97
+ # Idempotency-Key of a physical POS route: 8–200 printable ASCII characters, no space.
98
+ PHYSICAL_POS_IDEMPOTENCY_KEY_PATTERN = /\A[\x21-\x7E]{8,200}\z/
99
+ PHYSICAL_POS_MAX_LIMIT = 100
100
+ PHYSICAL_POS_ROW_VERSION_MAX = 2_147_483_647
101
+
102
+ # 5xx codes after which the gateway guarantees nothing was written (the payment did not start). Any
103
+ # other 5xx, and a request without an HTTP answer, leaves the outcome of a payment write unknown.
104
+ PHYSICAL_POS_NOT_STARTED_CODES = %w[
105
+ physical_pos.presence.unavailable physical_pos.signing.unavailable physical_pos.service.busy
106
+ physical_pos.service.clock_skew physical_pos.service.not_configured
107
+ ].freeze
108
+
109
+ PHYSICAL_POS_PAYMENT_TARGET_FIELDS = %w[deviceId vendorCode serialNumber externalRef].freeze
110
+ PHYSICAL_POS_SALE_ITEM_FIELDS = %w[lineNo name quantityMilli unitCode unitPriceMinor taxGroupCode lineTotalMinor barcode].freeze
111
+ PHYSICAL_POS_REFUND_ITEM_FIELDS = %w[lineNo quantityMilli amountMinor].freeze
112
+
113
+ # Request bodies: { field => kind }. Kinds: string, int, money, bool, strings (array of strings),
114
+ # rowVersion, target, saleItems, refundItems. A * suffix marks a required field; ? allows nil (an
115
+ # explicit clear, sent as JSON null).
116
+ PHYSICAL_POS_REQUEST_FIELDS = {
117
+ 'createPayment' => {
118
+ 'operation' => 'string*', 'target' => 'target*', 'amountMinor' => 'money*', 'currency' => 'string*',
119
+ 'installmentCount' => 'int?', 'instrument' => 'string?', 'merchantReference' => 'string?',
120
+ 'allowDuplicateReference' => 'bool', 'startTimeoutSeconds' => 'int?', 'terminalAcquirerId' => 'string?',
121
+ 'items' => 'saleItems', 'interaction' => 'string?', 'terminalProviderId' => 'string?'
122
+ },
123
+ 'createReversal' => {
124
+ 'operation' => 'string*', 'amountMinor' => 'money', 'currency' => 'string*', 'merchantReference' => 'string?',
125
+ 'startTimeoutSeconds' => 'int?', 'target' => 'target?', 'items' => 'refundItems'
126
+ },
127
+ 'createStore' => {
128
+ 'code' => 'string*', 'name' => 'string*', 'city' => 'string', 'district' => 'string', 'addressLine' => 'string',
129
+ 'timezone' => 'string', 'externalRef' => 'string'
130
+ },
131
+ 'updateStore' => {
132
+ 'rowVersion' => 'rowVersion*', 'name' => 'string', 'city' => 'string?', 'district' => 'string?',
133
+ 'addressLine' => 'string?', 'timezone' => 'string', 'externalRef' => 'string?'
134
+ },
135
+ 'statusChange' => { 'rowVersion' => 'rowVersion*', 'reasonCode' => 'string*' },
136
+ 'createRegister' => { 'code' => 'string*', 'name' => 'string*' },
137
+ 'updateRegister' => { 'rowVersion' => 'rowVersion*', 'name' => 'string' },
138
+ 'createTerminal' => {
139
+ 'code' => 'string*', 'displayName' => 'string*', 'vendorCode' => 'string', 'virtualSerial' => 'string',
140
+ 'vendorTerminalRef' => 'string'
141
+ },
142
+ 'updateTerminal' => { 'rowVersion' => 'rowVersion*', 'displayName' => 'string', 'vendorCode' => 'string' },
143
+ 'addTerminalAcquirer' => {
144
+ 'vendorAcquirerRef' => 'string*', 'merchantNumber' => 'string*', 'terminalNumber' => 'string*', 'label' => 'string',
145
+ 'currencies' => 'strings*'
146
+ },
147
+ 'updateTerminalAcquirer' => { 'rowVersion' => 'rowVersion*', 'label' => 'string?', 'currencies' => 'strings', 'status' => 'string' },
148
+ 'addTerminalProvider' => {
149
+ 'vendorAccountId' => 'string*', 'merchantCode' => 'string*', 'terminalCode' => 'string*', 'productCode' => 'string',
150
+ 'label' => 'string'
151
+ },
152
+ 'updateTerminalProvider' => { 'rowVersion' => 'rowVersion*', 'label' => 'string?', 'status' => 'string' },
153
+ 'changeTerminalDevice' => { 'rowVersion' => 'rowVersion*', 'deviceId' => 'string*', 'reasonCode' => 'string*' },
154
+ 'createDevice' => {
155
+ 'vendorCode' => 'string*', 'deviceModelId' => 'string*', 'serialNumber' => 'string*', 'displayName' => 'string',
156
+ 'externalRef' => 'string', 'storeId' => 'string', 'registerId' => 'string', 'integrationChannel' => 'string*',
157
+ 'channelVariant' => 'string', 'appMode' => 'string'
158
+ },
159
+ 'updateDevice' => {
160
+ 'rowVersion' => 'rowVersion*', 'displayName' => 'string?', 'externalRef' => 'string?', 'integrationChannel' => 'string',
161
+ 'channelVariant' => 'string?', 'appMode' => 'string?'
162
+ },
163
+ 'assignDevice' => { 'rowVersion' => 'rowVersion*', 'storeId' => 'string*', 'registerId' => 'string?', 'reasonCode' => 'string*' },
164
+ 'changeDeviceLifecycle' => { 'rowVersion' => 'rowVersion*', 'target' => 'string*', 'reasonCode' => 'string*' },
165
+ 'revokeDeviceKey' => { 'rowVersion' => 'rowVersion*', 'reasonCode' => 'string*' },
166
+ 'revertDeviceEnrollment' => { 'reasonCode' => 'string*' },
167
+ 'revokeActivationCode' => { 'reasonCode' => 'string*' },
168
+ 'setSettlementPolicy' => {
169
+ 'mode' => 'string*', 'scheduleTime' => 'string', 'timeZone' => 'string', 'scheduleDays' => 'strings',
170
+ 'retryWindowMinutes' => 'int', 'retryIntervalMinutes' => 'int', 'offlineBehavior' => 'string',
171
+ 'overdueAlertHours' => 'int', 'expectedRowVersion' => 'rowVersion'
172
+ }
173
+ }.transform_values(&:freeze).freeze
174
+
175
+ physical_pos_page = %w[limit cursor].freeze
176
+ physical_pos_entity_page = (physical_pos_page + ['includeTotal']).freeze
177
+ physical_pos_report = %w[dateFrom dateTo deviceId storeId].freeze
178
+
179
+ # Query parameters per route; anything else is rejected before sending. history covers the audit,
180
+ # link, assignment and key lists.
181
+ PHYSICAL_POS_FILTERS = {
182
+ 'listPayments' => physical_pos_page + %w[deviceId paymentStatus createdFrom createdTo merchantReference],
183
+ 'listTransactions' => physical_pos_page + %w[deviceId storeId registerId paymentStatus createdFrom createdTo merchantReference
184
+ amountFromMinor amountToMinor origin operation],
185
+ 'listAmbiguousPayments' => physical_pos_page + %w[deviceId paymentStatus],
186
+ 'getSalesSummary' => physical_pos_report + ['groupBy'],
187
+ 'getTaxSummary' => physical_pos_report,
188
+ 'listSettlements' => physical_pos_page + %w[deviceId lineStatus createdFrom createdTo],
189
+ 'listSettlementRuns' => physical_pos_entity_page + %w[deviceId source runStatus createdFrom createdTo],
190
+ 'listDeviceModels' => %w[vendorCode deviceType status],
191
+ 'listStores' => physical_pos_entity_page + %w[status q],
192
+ 'listRegisters' => physical_pos_entity_page + ['status'],
193
+ 'listTerminals' => physical_pos_entity_page + %w[status q],
194
+ 'listTerminalAcquirers' => physical_pos_entity_page,
195
+ 'listTerminalProviders' => physical_pos_entity_page,
196
+ 'listDevices' => physical_pos_entity_page + %w[storeId registerId vendorCode deviceModelId deviceType lifecycleStatus
197
+ ownershipStatus integrationChannel q],
198
+ 'history' => physical_pos_page
199
+ }.transform_values { |names| names.dup.freeze }.freeze
200
+
201
+ # Filters scanned for card numbers before sending.
202
+ PHYSICAL_POS_FREE_TEXT_FILTERS = %w[merchantReference q].freeze
203
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ module Lunixi
6
+ # One verified physical POS webhook (frozen).
7
+ #
8
+ # id: the event id (the same transition always carries the same id). type: physical_pos.payment.*,
9
+ # physical_pos.fiscal_document.* or physical_pos.settlement.*. category: payment, fiscal_document,
10
+ # settlement or other (a type a later release may add). environment: LIVE or TEST when present.
11
+ # created_at: when the transition happened (ISO 8601), when present. history_seq: the payment's /
12
+ # document's historySeq, or nil (end-of-day events carry none). original: a reversal's original
13
+ # payment { 'paymentId', 'origin' } (origin API or DEVICE_DIRECT), nil on a root payment. cashier:
14
+ # { 'cashierId', 'cashierCode' } for a payment started from a device cashier session, nil otherwise
15
+ # (the payload then has no cashier key). device_sale?: true for physical_pos.payment.device_sale, a
16
+ # sale made directly on the device (data carries origin and deviceOccurredAt). data: the payload.
17
+ # raw: the whole envelope.
18
+ PhysicalPosWebhookEvent = Struct.new(:id, :type, :category, :environment, :created_at, :history_seq, :original, :cashier,
19
+ :device_sale, :data, :raw, keyword_init: true) do
20
+ def device_sale?
21
+ device_sale == true
22
+ end
23
+ end
24
+
25
+ # Verifies and reads a physical POS webhook. There is no way in without the signature: pass the exact
26
+ # raw request body, the request headers and your webhook secret (or a configured WebhookVerifier).
27
+ # The signature, event id and timestamp are checked by WebhookVerifier; any mismatch raises
28
+ # WebhookError before the body is read.
29
+ #
30
+ # event = Lunixi::PhysicalPosWebhook.parse(request.raw_post, request.headers.to_h, secret)
31
+ # handle_approval(event.data) if event.type == Lunixi::PhysicalPosEvents::PAYMENT_APPROVED
32
+ #
33
+ # The event body is the envelope's data; an envelope that carries it under payloadJson (an object or
34
+ # that object as a JSON string) is read the same way. The type comes from the signed body only.
35
+ # Amounts in the payload are minor-unit strings ("4500"), matching the HTTP API, and are checked
36
+ # after the signature.
37
+ #
38
+ # Delivery order is not guaranteed and an event can arrive more than once: deduplicate by id and
39
+ # ignore an event whose history_seq is not greater than the last one you applied for the same
40
+ # data['paymentId']. End-of-day events (category settlement) carry no historySeq; deduplicate them by
41
+ # id. When in doubt, read the payment with get_payment.
42
+ module PhysicalPosWebhook
43
+ PREFIX = 'physical_pos.'
44
+ CATEGORY_PAYMENT = 'payment'
45
+ CATEGORY_FISCAL_DOCUMENT = 'fiscal_document'
46
+ CATEGORY_SETTLEMENT = 'settlement'
47
+ CATEGORY_OTHER = 'other'
48
+
49
+ module_function
50
+
51
+ # secret_or_verifier: your webhook secret, [current, *previous] secrets during rotation, or a
52
+ # WebhookVerifier. tolerance (seconds) is used only when secrets are given.
53
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
54
+ verified = verifier_for(secret_or_verifier, tolerance).verify(raw_body, headers)
55
+ envelope = verified.raw
56
+ type = text(envelope['type']) || text(envelope['eventType']) || verified.type
57
+ raise WebhookError, "Not a physical POS webhook event (type: #{type || 'missing'})" unless type.is_a?(String) && type.start_with?(PREFIX)
58
+
59
+ data = payload(envelope)
60
+ validate_money(data)
61
+ seq = data['historySeq']
62
+ PhysicalPosWebhookEvent.new(
63
+ id: text(envelope['id']) || text(envelope['eventId']) || verified.id, type: type, category: category(type),
64
+ environment: text(envelope['environment']),
65
+ created_at: text(envelope['createdAt']) || text(envelope['occurredAt']) || text(envelope['timestamp']),
66
+ history_seq: seq.is_a?(Integer) ? seq : nil, original: original(data), cashier: cashier(data),
67
+ device_sale: type == PhysicalPosEvents::PAYMENT_DEVICE_SALE, data: data, raw: envelope
68
+ ).freeze
69
+ end
70
+
71
+ # The original payment of a reversal event: { 'paymentId', 'origin' } when data['original'] carries
72
+ # both as non-empty strings (other keys are dropped); otherwise nil (a root payment).
73
+ def original(data)
74
+ pair(data, 'original', 'paymentId', 'origin')
75
+ end
76
+
77
+ # The cashier of a payment event: { 'cashierId', 'cashierCode' } when data['cashier'] carries both
78
+ # as non-empty strings (other keys are dropped); otherwise nil (no cashier session).
79
+ def cashier(data)
80
+ pair(data, 'cashier', 'cashierId', 'cashierCode')
81
+ end
82
+
83
+ # payment, fiscal_document, settlement or other.
84
+ def category(type)
85
+ return CATEGORY_PAYMENT if type.start_with?("#{PREFIX}payment.")
86
+ return CATEGORY_FISCAL_DOCUMENT if type.start_with?("#{PREFIX}fiscal_document.")
87
+ return CATEGORY_SETTLEMENT if type.start_with?("#{PREFIX}settlement.")
88
+
89
+ CATEGORY_OTHER
90
+ end
91
+
92
+ def pair(data, name, first, second)
93
+ value = data.is_a?(Hash) ? data[name] : nil
94
+ return nil unless value.is_a?(Hash)
95
+
96
+ left = text(value[first])
97
+ right = text(value[second])
98
+ left && right ? { first => left, second => right }.freeze : nil
99
+ end
100
+
101
+ def verifier_for(secret_or_verifier, tolerance)
102
+ return secret_or_verifier if secret_or_verifier.is_a?(WebhookVerifier)
103
+
104
+ unless secret_or_verifier.is_a?(String) || (secret_or_verifier.is_a?(Array) && !secret_or_verifier.empty?)
105
+ raise ConfigurationError, 'Pass your webhook secret (or [current, *previous] secrets) or a WebhookVerifier'
106
+ end
107
+
108
+ secrets = Array(secret_or_verifier)
109
+ WebhookVerifier.new(secret: secrets.first, previous_secrets: secrets.drop(1), tolerance: tolerance)
110
+ end
111
+
112
+ def payload(envelope)
113
+ data = envelope['data']
114
+ return data if data.is_a?(Hash) && !data.empty?
115
+
116
+ carried = envelope['payloadJson']
117
+ carried = parse_payload_json(carried) if carried.is_a?(String)
118
+ return deep_freeze(carried) if carried.is_a?(Hash) && !carried.empty?
119
+
120
+ raise WebhookError, 'The physical POS webhook carries no event data (data / payloadJson)'
121
+ end
122
+
123
+ def parse_payload_json(text)
124
+ JSON.parse(text, max_nesting: 64)
125
+ rescue JSON::ParserError
126
+ raise WebhookError, 'The physical POS webhook payloadJson is not valid JSON', cause: nil
127
+ end
128
+
129
+ def validate_money(data)
130
+ PhysicalPosMoney.validate(data)
131
+ rescue ConfigurationError
132
+ raise WebhookError, 'The physical POS webhook carries a non-canonical amount (minor-unit string expected)', cause: nil
133
+ end
134
+
135
+ def text(value)
136
+ value.is_a?(String) && !value.empty? ? value : nil
137
+ end
138
+
139
+ def deep_freeze(value)
140
+ case value
141
+ when Hash then value.each_value { |entry| deep_freeze(entry) }
142
+ when Array then value.each { |entry| deep_freeze(entry) }
143
+ end
144
+ value.freeze
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,106 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Lunixi
4
+ # One verified bank-connect, bank-transfer or insurance webhook (frozen). id: the event id (the same on
5
+ # every redelivery; deduplicate on it). type: one of the product's event names. environment: TEST or
6
+ # LIVE when present. created_at: the envelope's createdAt. data: the documented data fields of the
7
+ # event (a field the event did not carry is nil; no other key is kept). raw: the whole envelope.
8
+ ProductWebhookEvent = Struct.new(:id, :type, :environment, :created_at, :data, :raw, keyword_init: true) do
9
+ def [](name)
10
+ data[name.to_s]
11
+ end
12
+ end
13
+
14
+ # Reads product webhooks through the signature check, never around it. Not a public API; use
15
+ # BankConnectWebhook, BankTransferWebhook or InsuranceWebhook.
16
+ module ProductWebhook
17
+ module_function
18
+
19
+ # fields: { event type => data field list }. Amounts in data must be canonical minor-unit strings.
20
+ def parse(raw_body, headers, secret_or_verifier, fields, label, tolerance)
21
+ verified = PhysicalPosWebhook.verifier_for(secret_or_verifier, tolerance).verify(raw_body, headers)
22
+ read(verified, fields, label)
23
+ end
24
+
25
+ # An event already verified by WebhookVerifier#verify (or #process).
26
+ def read(verified, fields, label)
27
+ raise ConfigurationError, 'Pass a Lunixi::VerifiedEvent from WebhookVerifier#verify' unless verified.is_a?(VerifiedEvent)
28
+
29
+ list = fields[verified.type]
30
+ raise WebhookError, "Not a #{label} webhook event (type: #{verified.type})" if list.nil?
31
+
32
+ data = list.to_h { |name| [name, verified.data[name]] }
33
+ begin
34
+ Money.validate_fields(data, response: true)
35
+ rescue ConfigurationError
36
+ raise WebhookError, "The #{label} webhook carries a non-canonical amount (minor-unit string expected)", cause: nil
37
+ end
38
+ envelope = verified.raw
39
+ ProductWebhookEvent.new(id: verified.id, type: verified.type, environment: text(envelope['environment']),
40
+ created_at: text(envelope['createdAt']), data: data.freeze, raw: envelope).freeze
41
+ end
42
+
43
+ def text(value)
44
+ value.is_a?(String) && !value.empty? ? value : nil
45
+ end
46
+ end
47
+
48
+ # bank_account.transaction.received (BankConnectEvents): data holds
49
+ # BANK_ACCOUNT_TRANSACTION_RECEIVED_FIELDS.
50
+ #
51
+ # event = Lunixi::BankConnectWebhook.parse(request.raw_post, request.headers.to_h, secret)
52
+ # book(event['transactionId'], event['amountMinor']) unless seen?(event.id)
53
+ module BankConnectWebhook
54
+ FIELDS = BankConnectEvents::ALL.to_h { |type| [type, BANK_ACCOUNT_TRANSACTION_RECEIVED_FIELDS] }.freeze
55
+
56
+ module_function
57
+
58
+ # secret_or_verifier: your webhook secret, [current, *previous] secrets during rotation, or a
59
+ # WebhookVerifier. Raises WebhookError for a bad signature or another event type.
60
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
61
+ ProductWebhook.parse(raw_body, headers, secret_or_verifier, FIELDS, 'bank account', tolerance)
62
+ end
63
+
64
+ def from_event(verified_event)
65
+ ProductWebhook.read(verified_event, FIELDS, 'bank account')
66
+ end
67
+ end
68
+
69
+ # bank_transfer.* (BankTransferEvents, Bank Connect transfers): data holds BANK_TRANSFER_WEBHOOK_FIELDS.
70
+ # The event says what happened; read the current state with bank_connect.transfers.get.
71
+ module BankTransferWebhook
72
+ FIELDS = BankTransferEvents::ALL.to_h { |type| [type, BANK_TRANSFER_WEBHOOK_FIELDS] }.freeze
73
+
74
+ module_function
75
+
76
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
77
+ ProductWebhook.parse(raw_body, headers, secret_or_verifier, FIELDS, 'bank transfer', tolerance)
78
+ end
79
+
80
+ def from_event(verified_event)
81
+ ProductWebhook.read(verified_event, FIELDS, 'bank transfer')
82
+ end
83
+ end
84
+
85
+ # insurance.* (InsuranceEvents). An order event's data holds INSURANCE_WEBHOOK_FIELDS; the lead event
86
+ # (insurance.lead.submitted) holds INSURANCE_LEAD_WEBHOOK_FIELDS and is not an order. Decide on the
87
+ # order from the webhook; get_order shows its state.
88
+ module InsuranceWebhook
89
+ FIELDS = InsuranceEvents::ORDER_EVENTS.to_h { |type| [type, INSURANCE_WEBHOOK_FIELDS] }
90
+ .merge(InsuranceEvents::LEAD_SUBMITTED => INSURANCE_LEAD_WEBHOOK_FIELDS).freeze
91
+
92
+ module_function
93
+
94
+ def parse(raw_body, headers, secret_or_verifier, tolerance: 300)
95
+ ProductWebhook.parse(raw_body, headers, secret_or_verifier, FIELDS, 'insurance', tolerance)
96
+ end
97
+
98
+ def from_event(verified_event)
99
+ ProductWebhook.read(verified_event, FIELDS, 'insurance')
100
+ end
101
+
102
+ def lead_event?(event)
103
+ InsuranceEvents::LEAD_EVENTS.include?(event.type)
104
+ end
105
+ end
106
+ end