einvoice 1.4.0 → 2.0.0.alpha2

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 (66) hide show
  1. checksums.yaml +4 -4
  2. data/.coderabbit.yaml +12 -0
  3. data/.github/workflows/build.yml +7 -4
  4. data/CHANGELOG.md +55 -35
  5. data/Gemfile +3 -2
  6. data/README.md +230 -265
  7. data/README.zh-TW.md +322 -0
  8. data/Rakefile +2 -13
  9. data/bin/console +3 -6
  10. data/einvoice.gemspec +24 -21
  11. data/lib/einvoice/amego/client.rb +116 -0
  12. data/lib/einvoice/amego/errors.rb +84 -0
  13. data/lib/einvoice/amego/payload.rb +276 -0
  14. data/lib/einvoice/amego/provider.rb +267 -0
  15. data/lib/einvoice/amego.rb +27 -0
  16. data/lib/einvoice/capability.rb +79 -0
  17. data/lib/einvoice/ecpay/client.rb +183 -0
  18. data/lib/einvoice/ecpay/crypto.rb +85 -0
  19. data/lib/einvoice/ecpay/errors.rb +115 -0
  20. data/lib/einvoice/ecpay/payload.rb +241 -0
  21. data/lib/einvoice/ecpay/provider.rb +362 -0
  22. data/lib/einvoice/ecpay.rb +31 -0
  23. data/lib/einvoice/error.rb +220 -0
  24. data/lib/einvoice/ezpay/client.rb +130 -0
  25. data/lib/einvoice/ezpay/crypto.rb +85 -0
  26. data/lib/einvoice/ezpay/errors.rb +72 -0
  27. data/lib/einvoice/ezpay/payload.rb +269 -0
  28. data/lib/einvoice/ezpay/provider.rb +235 -0
  29. data/lib/einvoice/ezpay.rb +19 -0
  30. data/lib/einvoice/input.rb +494 -0
  31. data/lib/einvoice/mock_provider.rb +191 -0
  32. data/lib/einvoice/mof/donation_codes.rb +157 -0
  33. data/lib/einvoice/mof.rb +16 -0
  34. data/lib/einvoice/number.rb +51 -0
  35. data/lib/einvoice/provider.rb +57 -14
  36. data/lib/einvoice/redaction.rb +54 -0
  37. data/lib/einvoice/taipei.rb +89 -0
  38. data/lib/einvoice/tax_split.rb +124 -0
  39. data/lib/einvoice/tradevan/default_api/client.rb +175 -0
  40. data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
  41. data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
  42. data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
  43. data/lib/einvoice/tradevan/default_api/provider.rb +366 -0
  44. data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
  45. data/lib/einvoice/tradevan.rb +25 -0
  46. data/lib/einvoice/types.rb +323 -0
  47. data/lib/einvoice/version.rb +3 -1
  48. data/lib/einvoice.rb +21 -10
  49. metadata +60 -176
  50. data/.github/workflows/cron.yml +0 -31
  51. data/docs/Tradevan E-Invoice APIs.md +0 -201
  52. data/docs/neweb.md +0 -347
  53. data/lib/einvoice/client.rb +0 -21
  54. data/lib/einvoice/configuration.rb +0 -49
  55. data/lib/einvoice/connection.rb +0 -31
  56. data/lib/einvoice/donation_unit_list.json +0 -2022
  57. data/lib/einvoice/result.rb +0 -21
  58. data/lib/einvoice/tradevan/model/base.rb +0 -34
  59. data/lib/einvoice/tradevan/model/issue_data.rb +0 -129
  60. data/lib/einvoice/tradevan/model/issue_item.rb +0 -41
  61. data/lib/einvoice/tradevan/model/void_data.rb +0 -35
  62. data/lib/einvoice/tradevan/provider.rb +0 -140
  63. data/lib/einvoice/tradevan/result.rb +0 -25
  64. data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
  65. data/lib/einvoice/utils.rb +0 -13
  66. data/lib/faraday/response/decode_tradevan.rb +0 -38
@@ -0,0 +1,362 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module Einvoice
6
+ module ECPay
7
+ # {Einvoice::Provider} over ECPay's (綠界科技) B2C 電子發票 2.0 API.
8
+ #
9
+ # provider = Einvoice::ECPay::Provider.new(**Einvoice::ECPay::SANDBOX)
10
+ # result = provider.issue(order_id: "ORDER_1", ...)
11
+ #
12
+ # Credentials are per-instance, so a multi-merchant application holds one
13
+ # provider per merchant. +mode+ selects the stage (+:test+) or live
14
+ # (+:production+) host.
15
+ #
16
+ # Only the five unified operations plus carrier validation are mapped. ECPay
17
+ # has ~25 further B2C endpoints (延遲開立, 字軌設定, 列印, 通知 …); reach those
18
+ # through {#raw}, which handles the envelope and error mapping for any path.
19
+ class Provider < ::Einvoice::Provider
20
+ CAPABILITIES = Set[
21
+ Capability::ISSUE,
22
+ Capability::VOID,
23
+ Capability::ALLOWANCE,
24
+ Capability::VOID_ALLOWANCE,
25
+ Capability::QUERY,
26
+ Capability::B2B,
27
+ Capability::MIXED_TAX,
28
+ Capability::QUERY_BY_ORDER_ID,
29
+ Capability::CARRIER_VALIDATION
30
+ ].freeze
31
+
32
+ # ECPay ItemTaxType → unified 課稅別, for reading a queried invoice back.
33
+ TAX_CODE_TO_TYPE = Payload::TAX_TYPE.invert.freeze
34
+ # The only rate ECPay applies to a taxable line.
35
+ TAXABLE_RATE = Rational(5, 100)
36
+
37
+ attr_reader :capabilities, :client
38
+
39
+ # @param merchant_id [String] 特店編號
40
+ # @param hash_key [String] 16-byte AES HashKey — server-side only
41
+ # @param hash_iv [String] 16-byte AES HashIV — server-side only
42
+ # @param mode [Symbol] +:test+ (stage) or +:production+
43
+ # @param base_url [String, nil] override the host, e.g. in tests
44
+ # @param timeout [Integer] open/read timeout in seconds
45
+ # @param validate_payload [Boolean] check field rules locally before sending
46
+ def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST,
47
+ base_url: nil, timeout: 30, validate_payload: true)
48
+ super()
49
+ @client = Client.new(merchant_id: merchant_id, hash_key: hash_key, hash_iv: hash_iv,
50
+ mode: mode, base_url: base_url, timeout: timeout)
51
+ @validate_payload = validate_payload
52
+ @capabilities = CAPABILITIES
53
+ end
54
+
55
+ def name
56
+ Client::PROVIDER
57
+ end
58
+
59
+ # Call any B2C endpoint with a raw Data payload — the envelope, encryption
60
+ # and error mapping are applied as usual:
61
+ #
62
+ # provider.raw("/B2CInvoice/InvoicePrint", { "InvoiceNo" => "LA25000001" })
63
+ #
64
+ # Brace the payload: an unbraced hash would be read as this method's own
65
+ # keyword arguments.
66
+ def raw(path, data, success_codes: [], plain_data: false)
67
+ @client.request(path, data, success_codes: success_codes, plain_data: plain_data)
68
+ end
69
+
70
+ # 開立發票.
71
+ def issue(input)
72
+ parsed = Input.issue(input, provider: name)
73
+ assert_currency_supported!(parsed.currency)
74
+ assert_rate_supported!(parsed)
75
+ data = Payload.issue(parsed, validate: @validate_payload)
76
+ result = @client.request("/B2CInvoice/Issue", data)
77
+
78
+ IssueInvoiceResult.new(
79
+ invoice_number: result["InvoiceNo"].to_s,
80
+ invoice_datetime: parse_time(result["InvoiceDate"]),
81
+ random_code: result["RandomNumber"].to_s,
82
+ order_id: parsed.order_id,
83
+ total_amount: parsed.amount.total_amount,
84
+ buyer_ubn: parsed.buyer&.ubn,
85
+ tax_type: TaxType.of(parsed.items, parsed.tax_type),
86
+ tax_rate: parsed.tax_rate,
87
+ status: InvoiceStatus::ISSUED,
88
+ raw: result
89
+ )
90
+ end
91
+
92
+ # 作廢發票. ECPay keys the void on the invoice's issue date, so the reference
93
+ # needs invoice_datetime, or an order_id to look it up (see invoice_date).
94
+ #
95
+ # An invoice with a live 折讓 cannot be voided (+:void_blocked_by_allowance+);
96
+ # void the allowance first.
97
+ def void(input)
98
+ parsed = Input.void(input, provider: name)
99
+
100
+ result = @client.request("/B2CInvoice/Invalid", {
101
+ "InvoiceNo" => parsed.invoice.number,
102
+ "InvoiceDate" => invoice_date(parsed.invoice, "void"),
103
+ "Reason" => parsed.reason
104
+ })
105
+ VoidInvoiceResult.new(invoice_number: parsed.invoice.number,
106
+ status: InvoiceStatus::VOIDED, raw: result)
107
+ end
108
+
109
+ # 開立折讓 (紙本). Returns the 折讓單號 immediately; it can be voided right away.
110
+ # Defaults to notifying nobody — pass
111
+ # <tt>provider_options: { allowance_notify: "E", notify_mail: "..." }</tt> to
112
+ # have ECPay tell the buyer (S 簡訊 / E 信箱 / A 兩者 / N 不通知).
113
+ def allowance(input)
114
+ parsed = Input.allowance(input, provider: name)
115
+ assert_rate_supported!(parsed)
116
+ options = Payload.string_keys(parsed.provider_options)
117
+
118
+ data = {
119
+ "InvoiceNo" => parsed.invoice.number,
120
+ "AllowanceNotify" => options["allowance_notify"] || "N",
121
+ "CustomerName" => options["customer_name"],
122
+ "NotifyMail" => options["notify_mail"],
123
+ "NotifyPhone" => options["notify_phone"],
124
+ "AllowanceAmount" => parsed.amount.total_amount,
125
+ "Reason" => options["reason"],
126
+ "Items" => Payload.allowance_items(parsed)
127
+ }.compact
128
+ Payload.check_allowance!(data) if @validate_payload
129
+ data["InvoiceDate"] = invoice_date(parsed.invoice, "allowance")
130
+ result = @client.request("/B2CInvoice/Allowance", data)
131
+
132
+ AllowanceResult.new(
133
+ allowance_number: result["IA_Allow_No"].to_s,
134
+ invoice_number: result["IA_Invoice_No"] || parsed.invoice.number,
135
+ allowance_date: parse_time(result["IA_Date"])&.to_date,
136
+ total_amount: parsed.amount.total_amount,
137
+ raw: result
138
+ )
139
+ end
140
+
141
+ # 作廢折讓. Voids one 折讓單, not the invoice. ECPay needs the invoice number
142
+ # too, so a plain allowance number is not enough.
143
+ def void_allowance(input)
144
+ parsed = Input.void_allowance(input, provider: name)
145
+ allowance = parsed.allowance
146
+ if allowance.invoice_number.nil?
147
+ raise ValidationError.new("void_allowance needs allowance.invoice_number", provider: name)
148
+ end
149
+
150
+ result = @client.request("/B2CInvoice/AllowanceInvalid", {
151
+ "InvoiceNo" => allowance.invoice_number,
152
+ "AllowanceNo" => allowance.allowance_number,
153
+ "Reason" => parsed.reason
154
+ })
155
+ VoidAllowanceResult.new(allowance_number: allowance.allowance_number, raw: result)
156
+ end
157
+
158
+ # 查詢發票. By invoice number when the reference has the number and the
159
+ # issue date, which ECPay pairs with it. Otherwise by 自訂編號. A query by
160
+ # 自訂編號 for a reference with a number checks that ECPay found that
161
+ # number, as an order id may belong to another invoice.
162
+ def query(input)
163
+ reference = Input.query(input, provider: name).invoice
164
+ if reference.order_id && (reference.number.nil? || reference.invoice_datetime.nil?)
165
+ assert_supports!(Capability::QUERY_BY_ORDER_ID)
166
+ return query_by_order_id(reference.order_id, number: reference.number)
167
+ end
168
+
169
+ if reference.invoice_datetime.nil?
170
+ raise ValidationError.new("query by number needs invoice.invoice_datetime", provider: name)
171
+ end
172
+
173
+ result = @client.request("/B2CInvoice/GetIssue", {
174
+ "InvoiceNo" => reference.number,
175
+ "InvoiceDate" => format_date(reference.invoice_datetime)
176
+ })
177
+ build_query_result(result, reference)
178
+ end
179
+
180
+ # Whether a carrier is registered. ECPay can check a 手機條碼 only.
181
+ def validate_carrier(carrier)
182
+ parsed = Input.carrier(carrier, provider: name)
183
+ unless parsed.type == CarrierType::MOBILE_BARCODE
184
+ raise UnsupportedError.new("ECPay can check a mobile barcode only, not #{parsed.type}", provider: name)
185
+ end
186
+
187
+ @client.request("/B2CInvoice/CheckBarcode", { "BarCode" => parsed.code })["IsExist"] == "Y"
188
+ end
189
+
190
+ # 愛心碼驗證 — whether a donation code is registered.
191
+ def validate_love_code(love_code)
192
+ !love_code_organ_name(love_code).nil?
193
+ end
194
+
195
+ # The receiving organisation's name for a 愛心碼, or +nil+ when unregistered.
196
+ def love_code_organ_name(love_code)
197
+ if @validate_payload && !love_code.to_s.match?(Donation::CODE_FORMAT)
198
+ raise ValidationError.new("Invalid love code: #{love_code.inspect}", provider: name)
199
+ end
200
+
201
+ result = @client.request("/B2CInvoice/CheckLoveCode", { "LoveCode" => love_code })
202
+ return nil unless result["IsExist"] == "Y"
203
+
204
+ name = result["OrganName"].to_s
205
+ name.empty? ? nil : name
206
+ end
207
+
208
+ private
209
+
210
+ # ECPay fixes the rate by TaxType. A taxable line is always 5%.
211
+ def assert_rate_supported!(parsed)
212
+ taxable = parsed.items.any? { |item| (item.tax_type || parsed.tax_type) == TaxType::TAXABLE }
213
+ return unless taxable && parsed.tax_rate != TAXABLE_RATE
214
+
215
+ raise UnsupportedError.new("ECPay taxes a taxable invoice at 0.05 only, got #{parsed.tax_rate.to_f}",
216
+ provider: name)
217
+ end
218
+
219
+ def build_query_result(result, reference)
220
+ total = result["IIS_Sales_Amount"].to_i
221
+ tax = result["IIS_Tax_Amount"].to_i
222
+ items = build_items(result["Items"])
223
+ tax_type = items.empty? ? nil : TaxType.of(items, nil)
224
+
225
+ QueryInvoiceResult.new(
226
+ invoice_number: result["IIS_Number"] || reference.number.to_s,
227
+ invoice_datetime: parse_time(result["IIS_Create_Date"]),
228
+ random_code: result["IIS_Random_Number"].to_s,
229
+ order_id: result["IIS_Relate_Number"] || reference.order_id,
230
+ status: derive_status(result),
231
+ amount: AmountSummary.new(sales_amount: total - tax, tax_amount: tax,
232
+ total_amount: total),
233
+ buyer: build_buyer(result),
234
+ items: items,
235
+ tax_type: tax_type,
236
+ tax_rate: query_rate(tax_type, result["IIS_Tax_Rate"]),
237
+ raw: result
238
+ )
239
+ end
240
+
241
+ # ECPay fixes the rate of a taxable, zero-rated or tax-free invoice. A
242
+ # special-tax invoice has its own rate, which GetIssue returns. A rate
243
+ # that is not a MIG rate reads as nil, so an allowance has to give one.
244
+ def query_rate(tax_type, reported)
245
+ case tax_type
246
+ when TaxType::TAXABLE, TaxType::MIXED then TAXABLE_RATE
247
+ when TaxType::ZERO_RATED, TaxType::TAX_FREE then 0r
248
+ when TaxType::SPECIAL
249
+ begin
250
+ Input.mig_rate!(reported, "IIS_Tax_Rate", name)
251
+ rescue ValidationError
252
+ nil
253
+ end
254
+ end
255
+ end
256
+
257
+ def build_buyer(result)
258
+ Buyer.new(
259
+ name: presence(result["IIS_Customer_Name"]),
260
+ # ECPay fills a B2C invoice's 統編 with a zero placeholder.
261
+ ubn: presence(result["IIS_Identifier"], placeholder: "0000000000"),
262
+ email: presence(result["IIS_Customer_Email"]),
263
+ address: presence(result["IIS_Customer_Addr"]),
264
+ phone: presence(result["IIS_Customer_Phone"])
265
+ )
266
+ end
267
+
268
+ def build_items(rows)
269
+ Array(rows).map do |row|
270
+ InvoiceItem.new(
271
+ description: row["ItemName"].to_s,
272
+ quantity: numeric(row["ItemCount"]),
273
+ unit_price: numeric(row["ItemPrice"]),
274
+ amount: numeric(row["ItemAmount"]),
275
+ unit: presence(row["ItemWord"]),
276
+ tax_type: TAX_CODE_TO_TYPE[row["ItemTaxType"].to_s],
277
+ remark: presence(row["ItemRemark"])
278
+ )
279
+ end
280
+ end
281
+
282
+ # ECPay reports the lifecycle across two fields: an explicit void flag, and
283
+ # the remaining creditable amount falling below the sales total once a 折讓
284
+ # exists.
285
+ def derive_status(result)
286
+ # 註銷 (cancelled) has no unified status.
287
+ return nil if result["IIS_Issue_Status"].to_s == "0"
288
+ return InvoiceStatus::VOIDED if result["IIS_Invalid_Status"].to_s == "1"
289
+
290
+ sales = result["IIS_Sales_Amount"].to_i
291
+ remaining = result.fetch("IIS_Remain_Allowance_Amt", sales).to_i
292
+ return InvoiceStatus::ALLOWANCE if sales.positive? && remaining < sales
293
+
294
+ InvoiceStatus::ISSUED
295
+ end
296
+
297
+ # ECPay returns amounts as JSON numbers; keep integers integral.
298
+ def numeric(value)
299
+ float = value.to_f
300
+ float == float.to_i ? float.to_i : float
301
+ end
302
+
303
+ def presence(value, placeholder: nil)
304
+ string = value.to_s
305
+ string.empty? || string == placeholder ? nil : string
306
+ end
307
+
308
+ # "2026-08-15 23:02:23" (Asia/Taipei) → Time. Falls back to nil so a missing
309
+ # date never masquerades as "now".
310
+ def parse_time(value)
311
+ match = /\A(\d{4})[-\/](\d{2})[-\/](\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2}))?/.match(value.to_s.strip)
312
+ return nil unless match
313
+
314
+ year, month, day, hour, minute, second = match.captures
315
+ Time.new(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, second.to_i, "+08:00")
316
+ end
317
+
318
+ # +number+, when given, is the invoice the caller means. ECPay returns
319
+ # the invoice that has the order id now, so a different number is an
320
+ # error, not a result.
321
+ def query_by_order_id(order_id, number: nil)
322
+ result = @client.request("/B2CInvoice/GetIssue", { "RelateNumber" => order_id })
323
+ found = build_query_result(result, InvoiceReference.new(order_id: order_id))
324
+ if number && found.invoice_number != number
325
+ raise ProviderError.new("ECPay found invoice #{found.invoice_number} for order id #{order_id}, " \
326
+ "not #{number}", provider: name, raw: result)
327
+ end
328
+ found
329
+ end
330
+
331
+ # The issue date that Invalid, Allowance and GetIssue ask for. Taken from the
332
+ # reference, else looked up by order id. A failed lookup is the provider's
333
+ # error, not the invoice's: a NotFoundError would read as "the invoice of
334
+ # this call does not exist".
335
+ def invoice_date(reference, operation)
336
+ return format_date(reference.invoice_datetime) if reference.invoice_datetime
337
+
338
+ if reference.order_id.nil?
339
+ raise ValidationError.new("#{operation} needs invoice.invoice_datetime, or invoice.order_id to look it up",
340
+ provider: name)
341
+ end
342
+
343
+ found = begin
344
+ query_by_order_id(reference.order_id, number: reference.number)
345
+ rescue Error => e
346
+ raise ProviderError.new("#{operation} needs invoice.invoice_datetime; looking it up by order id failed: " \
347
+ "#{e.message}", provider: name, reason: Reason::LOOKUP_FAILED, cause: e)
348
+ end
349
+ if found.invoice_datetime.nil?
350
+ raise ProviderError.new("#{operation} needs invoice.invoice_datetime; the invoice found by order id has " \
351
+ "no issue date", provider: name, reason: Reason::LOOKUP_FAILED)
352
+ end
353
+ format_date(found.invoice_datetime)
354
+ end
355
+
356
+ # ECPay dates are Taipei-local.
357
+ def format_date(time)
358
+ Taipei.date(time, provider: name).strftime("%Y-%m-%d")
359
+ end
360
+ end
361
+ end
362
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "einvoice"
4
+ require "einvoice/ecpay/crypto"
5
+ require "einvoice/ecpay/errors"
6
+ require "einvoice/ecpay/client"
7
+ require "einvoice/ecpay/payload"
8
+ require "einvoice/ecpay/provider"
9
+
10
+ module Einvoice
11
+ # Adapter for ECPay 綠界科技's B2C 電子發票 2.0 API.
12
+ #
13
+ # The wire format is a JSON envelope whose +Data+ field is AES-128-CBC
14
+ # encrypted with the merchant's HashKey/HashIV, and every response carries two
15
+ # independent result codes ({Errors} explains the split). None of that reaches
16
+ # application code: {Provider} exposes only the unified model.
17
+ #
18
+ # provider = Einvoice::ECPay::Provider.new(**Einvoice::ECPay::SANDBOX)
19
+ # provider.issue(order_id: "ORDER_1", ...) # => Einvoice::IssueInvoiceResult
20
+ module ECPay
21
+ # ECPay's published shared **sandbox** credentials for the B2C e-invoice API.
22
+ # They let you try the adapter against the stage host with no account of your
23
+ # own — and are shared with every other developer doing the same, so never use
24
+ # them for anything real.
25
+ SANDBOX = {
26
+ merchant_id: "2000132",
27
+ hash_key: "ejCk326UnaZWKisg",
28
+ hash_iv: "q9jcZX8Ib9LM8wYk"
29
+ }.freeze
30
+ end
31
+ end
@@ -0,0 +1,220 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "timeout"
6
+
7
+ module Einvoice
8
+ # Normalized, action-oriented reason symbols — one level finer than the error
9
+ # class. The classes are deliberately coarse ({ConflictError} alone covers
10
+ # duplicate-order, void-blocked-by-allowance, already-voided and past-deadline,
11
+ # which a caller handles completely differently), so `reason` carries the
12
+ # distinction. `nil` when the adapter cannot determine one.
13
+ #
14
+ # Each value implies a concrete consumer action, e.g. +:duplicate_order+ →
15
+ # query-and-adopt the existing invoice; +:void_blocked_by_allowance+ → issue an
16
+ # allowance instead; +:already_voided+ → treat as idempotent success.
17
+ #
18
+ # That last one is why the two "wrong state" reasons are separate. Voiding an
19
+ # already-voided invoice reached the state the caller wanted, so doing nothing
20
+ # is correct. Crediting a voided invoice did not: no allowance exists, and
21
+ # treating it as success would record a refund that never happened.
22
+ module Reason
23
+ DUPLICATE_ORDER = :duplicate_order
24
+ # 作廢 refused: the invoice carries a live 折讓 — void that first.
25
+ VOID_BLOCKED_BY_ALLOWANCE = :void_blocked_by_allowance
26
+ # 折讓 refused: the invoice is already 作廢 — there is nothing to credit, and
27
+ # nothing was credited. Not idempotent success; the caller has to reconcile.
28
+ ALLOWANCE_BLOCKED_BY_VOID = :allowance_blocked_by_void
29
+ # 作廢 of an invoice already 作廢 — the requested state, so safe to ignore.
30
+ ALREADY_VOIDED = :already_voided
31
+ DUPLICATE_ALLOWANCE = :duplicate_allowance
32
+ PAST_DEADLINE = :past_deadline
33
+ CARRIER_NOT_REGISTERED = :carrier_not_registered
34
+ RATE_LIMITED = :rate_limited
35
+ CREDENTIALS_INVALID = :credentials_invalid
36
+ NOT_ENROLLED = :not_enrolled
37
+ CONTRACT_EXPIRED = :contract_expired
38
+ IP_BLOCKED = :ip_blocked
39
+ ACCOUNT_SUSPENDED = :account_suspended
40
+ # The provider refused the request time. The caller's server clock is off.
41
+ # An AuthError at every provider: the request is checked with its time, and
42
+ # a retry fails the same way until the clock is fixed. The shared ECPay
43
+ # fixtures, which the TypeScript SDK runs too, pin it as AUTH.
44
+ STALE_TIMESTAMP = :stale_timestamp
45
+ # The adapter queried the provider on its own, to fill a field the call did
46
+ # not give, and that query failed. +cause+ holds the error of the query.
47
+ # A provider error: the invoice of the call may well exist.
48
+ LOOKUP_FAILED = :lookup_failed
49
+ # The provider says "not now": the invoice is still being issued, a change
50
+ # waits in its queue, or it is not uploaded yet. The same call may work
51
+ # later. A ConflictError, as the state is wrong for now.
52
+ RETRY_LATER = :retry_later
53
+
54
+ ALL = [
55
+ DUPLICATE_ORDER, VOID_BLOCKED_BY_ALLOWANCE, ALLOWANCE_BLOCKED_BY_VOID,
56
+ ALREADY_VOIDED, DUPLICATE_ALLOWANCE,
57
+ PAST_DEADLINE, CARRIER_NOT_REGISTERED, RATE_LIMITED, CREDENTIALS_INVALID,
58
+ NOT_ENROLLED, CONTRACT_EXPIRED, IP_BLOCKED, ACCOUNT_SUSPENDED, STALE_TIMESTAMP,
59
+ LOOKUP_FAILED, RETRY_LATER
60
+ ].freeze
61
+ end
62
+
63
+ # Base class for every error the SDK raises. Adapters map provider/MOF error
64
+ # codes onto a subclass, preserving the provider's raw code/message/payload.
65
+ #
66
+ # Rescue precisely (`rescue Einvoice::ConflictError`) or broadly
67
+ # (`rescue Einvoice::Error`) — the subclass hierarchy replaces the string
68
+ # matching the legacy client forced on callers. Each subclass exposes a stable
69
+ # {#code} symbol so two-way parity with the TypeScript SDK's InvoiceErrorCode
70
+ # holds.
71
+ class Error < StandardError
72
+ # Stable, provider-independent code for the base class. Subclasses override.
73
+ CODE = :unknown
74
+ # Which side failed. +:invoice+: the request breaks a rule of the MOF, or the
75
+ # invoice is not in the state it needs. These mean the same at every
76
+ # provider. +:provider+: the account, the connection, the provider's own
77
+ # service, or a feature it lacks.
78
+ GROUP = :provider
79
+ # The low-level errors that mean the connection failed. Clients rescue only
80
+ # these, so a bug in an adapter is not reported as a NetworkError.
81
+ NETWORK_ERRORS = [
82
+ IOError, SocketError, SystemCallError, Timeout::Error, EOFError,
83
+ OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError
84
+ ].freeze
85
+
86
+ attr_reader :provider, :reason, :raw_code, :raw_message, :raw
87
+
88
+ def initialize(message = nil, provider:, reason: nil, raw_code: nil, raw_message: nil,
89
+ raw: nil, cause: nil)
90
+ super(message)
91
+ @provider = provider
92
+ @reason = reason
93
+ @raw_code = raw_code
94
+ @raw_message = raw_message
95
+ @raw = raw
96
+ @explicit_cause = cause
97
+ end
98
+
99
+ # The stable {InvoiceErrorCode}-equivalent symbol, e.g. +:conflict+.
100
+ def code
101
+ self.class::CODE
102
+ end
103
+
104
+ # +:invoice+ or +:provider+. See {GROUP}.
105
+ def group
106
+ self.class::GROUP
107
+ end
108
+
109
+ # Preserve an explicitly-passed cause, else fall back to Ruby's ambient one.
110
+ def cause
111
+ @explicit_cause || super
112
+ end
113
+
114
+ # Structured-logging shape. Omits +raw+ (can be large / carry PII — read it
115
+ # off the instance when needed) and drops nil fields.
116
+ def to_h
117
+ {
118
+ provider: provider,
119
+ code: code,
120
+ group: group,
121
+ reason: reason,
122
+ message: message,
123
+ raw_code: raw_code,
124
+ raw_message: raw_message
125
+ }.compact
126
+ end
127
+
128
+ # Build the subclass for a normalized code symbol. Adapters resolve a
129
+ # provider code to one of our codes, then `raise Einvoice::Error.for(code, …)`.
130
+ def self.for(code, message = nil, **options)
131
+ CODE_TO_CLASS.fetch(code, UnknownError).new(message, **options)
132
+ end
133
+ end
134
+
135
+ # Auth / signature / credential failure.
136
+ class AuthError < Error
137
+ CODE = :auth
138
+ end
139
+
140
+ # Request failed local or remote validation.
141
+ class ValidationError < Error
142
+ CODE = :validation
143
+ GROUP = :invoice
144
+ end
145
+
146
+ # Referenced invoice/allowance does not exist.
147
+ class NotFoundError < Error
148
+ CODE = :not_found
149
+ GROUP = :invoice
150
+ end
151
+
152
+ # Operation invalid for the invoice's current state (e.g. void a voided one).
153
+ class ConflictError < Error
154
+ CODE = :conflict
155
+ GROUP = :invoice
156
+ end
157
+
158
+ # 字軌 / 配號 exhausted — no invoice number available.
159
+ class NumberExhaustedError < Error
160
+ CODE = :number_exhausted
161
+ GROUP = :invoice
162
+ end
163
+
164
+ # Network / timeout / transport failure, and HTTP 5xx or 429. The caller can
165
+ # retry.
166
+ class NetworkError < Error
167
+ CODE = :network
168
+
169
+ # The error for an HTTP status that means "try again", or nil.
170
+ def self.for_status(response, provider:)
171
+ status = response.code.to_i
172
+ return unless status == 429 || status >= 500
173
+
174
+ reason = status == 429 ? Reason::RATE_LIMITED : nil
175
+ new("#{provider} returned HTTP #{status}", provider: provider, reason: reason, raw_code: response.code)
176
+ end
177
+
178
+ # The error for a connection failure. +response+ is the response whose
179
+ # headers had arrived before the failure, or nil. Its status is kept, so a
180
+ # body that failed to arrive after HTTP 429 is still RATE_LIMITED. +name+
181
+ # is the provider's name for the message, such as "ECPay".
182
+ def self.for_failure(cause, provider:, name: provider, response: nil)
183
+ message = "#{name} request failed: #{cause.message}"
184
+ return new(message, provider: provider, cause: cause) unless response
185
+
186
+ reason = response.code.to_i == 429 ? Reason::RATE_LIMITED : nil
187
+ new("#{message} (HTTP #{response.code})", provider: provider, reason: reason, raw_code: response.code,
188
+ cause: cause)
189
+ end
190
+ end
191
+
192
+ # Provider returned an error we could not map.
193
+ class ProviderError < Error
194
+ CODE = :provider
195
+ end
196
+
197
+ # The provider does not support the requested operation/feature.
198
+ class UnsupportedError < Error
199
+ CODE = :unsupported
200
+ end
201
+
202
+ # Anything else.
203
+ class UnknownError < Error
204
+ CODE = :unknown
205
+ end
206
+
207
+ class Error
208
+ CODE_TO_CLASS = {
209
+ auth: AuthError,
210
+ validation: ValidationError,
211
+ not_found: NotFoundError,
212
+ conflict: ConflictError,
213
+ number_exhausted: NumberExhaustedError,
214
+ network: NetworkError,
215
+ provider: ProviderError,
216
+ unsupported: UnsupportedError,
217
+ unknown: UnknownError
218
+ }.freeze
219
+ end
220
+ end