einvoice 1.5.0 → 2.0.0.beta1

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 +6 -8
  3. data/.github/workflows/build.yml +6 -3
  4. data/.github/workflows/cron.yml +4 -2
  5. data/CHANGELOG.md +63 -44
  6. data/Gemfile +3 -10
  7. data/README.md +284 -325
  8. data/README.zh-TW.md +381 -0
  9. data/Rakefile +2 -51
  10. data/bin/console +3 -6
  11. data/einvoice.gemspec +17 -18
  12. data/lib/einvoice/amego/client.rb +116 -0
  13. data/lib/einvoice/amego/errors.rb +84 -0
  14. data/lib/einvoice/amego/payload.rb +270 -0
  15. data/lib/einvoice/amego/provider.rb +272 -0
  16. data/lib/einvoice/amego.rb +27 -0
  17. data/lib/einvoice/capability.rb +79 -0
  18. data/lib/einvoice/ecpay/client.rb +184 -0
  19. data/lib/einvoice/ecpay/crypto.rb +85 -0
  20. data/lib/einvoice/ecpay/errors.rb +115 -0
  21. data/lib/einvoice/ecpay/payload.rb +241 -0
  22. data/lib/einvoice/ecpay/provider.rb +371 -0
  23. data/lib/einvoice/ecpay.rb +31 -0
  24. data/lib/einvoice/error.rb +220 -0
  25. data/lib/einvoice/ezpay/client.rb +130 -0
  26. data/lib/einvoice/ezpay/crypto.rb +85 -0
  27. data/lib/einvoice/ezpay/errors.rb +72 -0
  28. data/lib/einvoice/ezpay/payload.rb +269 -0
  29. data/lib/einvoice/ezpay/provider.rb +253 -0
  30. data/lib/einvoice/ezpay.rb +19 -0
  31. data/lib/einvoice/input.rb +547 -0
  32. data/lib/einvoice/mock_provider.rb +191 -0
  33. data/lib/einvoice/mof/donation_codes.rb +157 -0
  34. data/lib/einvoice/mof.rb +16 -0
  35. data/lib/einvoice/number.rb +91 -0
  36. data/lib/einvoice/provider.rb +57 -13
  37. data/lib/einvoice/redaction.rb +54 -0
  38. data/lib/einvoice/taipei.rb +89 -0
  39. data/lib/einvoice/tax_split.rb +112 -0
  40. data/lib/einvoice/tradevan/default_api/client.rb +175 -0
  41. data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
  42. data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
  43. data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
  44. data/lib/einvoice/tradevan/default_api/provider.rb +353 -0
  45. data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
  46. data/lib/einvoice/tradevan.rb +25 -0
  47. data/lib/einvoice/types.rb +365 -0
  48. data/lib/einvoice/version.rb +3 -1
  49. data/lib/einvoice.rb +21 -9
  50. metadata +52 -144
  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 -2025
  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 -139
  63. data/lib/einvoice/tradevan/result.rb +0 -25
  64. data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
  65. data/lib/faraday/response/decode_tradevan.rb +0 -37
  66. data/lib/faraday/response/parse_xml.rb +0 -14
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Einvoice
4
+ # Feature flags a provider may or may not support. Every adapter declares its
5
+ # own set so callers feature-detect at runtime ({Capability::Support#supports?})
6
+ # instead of discovering a gap only when a request fails.
7
+ #
8
+ # The five core operations are listed so a degraded/partial adapter can be
9
+ # honest about what it omits; the rest cover optional behaviour that genuinely
10
+ # differs between value-added centers.
11
+ module Capability
12
+ # 開立發票.
13
+ ISSUE = :issue
14
+ # 作廢發票.
15
+ VOID = :void
16
+ # 開立折讓.
17
+ ALLOWANCE = :allowance
18
+ # 作廢折讓.
19
+ VOID_ALLOWANCE = :void_allowance
20
+ # 查詢發票.
21
+ QUERY = :query
22
+ # Issue to a business buyer with a 統一編號 (B2B).
23
+ B2B = :b2b
24
+ # Mixed tax-rate invoice (應稅 + 零稅率 + 免稅 in one document).
25
+ MIXED_TAX = :mixed_tax
26
+ # Look up an invoice by the merchant order id, not just the invoice number.
27
+ QUERY_BY_ORDER_ID = :query_by_order_id
28
+ # Schedule an invoice to be issued automatically at a future date. No
29
+ # adapter declares it and the unified model has no method for it yet: at
30
+ # ECPay a delayed issue calls the merchant back, and 2.0 has no callbacks.
31
+ # It stays so that a later version can add the feature.
32
+ SCHEDULED_ISSUE = :scheduled_issue
33
+ # Validate a carrier (手機條碼 / 愛心碼) against the tax authority.
34
+ CARRIER_VALIDATION = :carrier_validation
35
+ # Annotate a foreign-currency sale via currency + exchange_rate. Statutory
36
+ # amounts are still filed in integer TWD; providers that don't support it
37
+ # reject a non-TWD currency instead of silently dropping it.
38
+ FOREIGN_CURRENCY = :foreign_currency
39
+
40
+ ALL = [
41
+ ISSUE, VOID, ALLOWANCE, VOID_ALLOWANCE, QUERY, B2B, MIXED_TAX,
42
+ QUERY_BY_ORDER_ID, SCHEDULED_ISSUE, CARRIER_VALIDATION, FOREIGN_CURRENCY
43
+ ].freeze
44
+
45
+ # Mixed into anything that exposes a +#capabilities+ set and a +#name+.
46
+ module Support
47
+ # The MIG filing currency. Anything else needs FOREIGN_CURRENCY.
48
+ TWD = "TWD"
49
+
50
+ # Whether this provider declares support for +capability+.
51
+ def supports?(capability)
52
+ capabilities.include?(capability)
53
+ end
54
+
55
+ # Raise {UnsupportedError} unless this provider supports +capability+.
56
+ def assert_supports!(capability)
57
+ return if supports?(capability)
58
+
59
+ raise Einvoice::UnsupportedError.new(
60
+ %(Provider "#{name}" does not support capability "#{capability}"),
61
+ provider: name
62
+ )
63
+ end
64
+
65
+ # Statutory amounts are always filed in TWD, so a +currency+ is an
66
+ # annotation of the original sale that only some centers can carry. Every
67
+ # adapter owes the caller the same answer here — refuse rather than file a
68
+ # foreign-currency sale as though it were TWD — so the check lives once.
69
+ #
70
+ # It belongs to the provider rather than to {Input}, which knows a provider
71
+ # only by name and has no capability set to consult.
72
+ def assert_currency_supported!(currency)
73
+ return if currency.nil? || currency == TWD
74
+
75
+ assert_supports!(Capability::FOREIGN_CURRENCY)
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,184 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+
7
+ module Einvoice
8
+ module ECPay
9
+ # Speaks the ECPay B2C wire protocol: wrap a payload Hash as
10
+ # <tt>{ MerchantID, RqHeader: { Timestamp, Revision }, Data: <encrypted> }</tt>,
11
+ # POST it as JSON, then unwrap and check both result layers, raising the
12
+ # matching {Einvoice::Error} subclass.
13
+ #
14
+ # Callers get the decrypted business payload back and never see the envelope.
15
+ class Client
16
+ PROVIDER = "ecpay"
17
+
18
+ # B2C 電子發票 hosts.
19
+ BASE_URL = {
20
+ test: "https://einvoice-stage.ecpay.com.tw",
21
+ production: "https://einvoice.ecpay.com.tw"
22
+ }.freeze
23
+
24
+ # Sent in every RqHeader. The current B2C docs do not list Revision. Stage
25
+ # takes any value, or none, and sends it back (checked by hand on
26
+ # 2026-11-27). It stays until docs/providers/ecpay/b2c.md, open question 1,
27
+ # is settled.
28
+ REVISION = "3.0.0"
29
+
30
+ attr_reader :merchant_id, :mode, :base_url, :timeout
31
+
32
+ def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST,
33
+ base_url: nil, timeout: 30)
34
+ @merchant_id = merchant_id.to_s
35
+ @hash_key = hash_key.to_s
36
+ @hash_iv = hash_iv.to_s
37
+ @mode = mode
38
+ @base_url = Redaction.base_url!(base_url || BASE_URL.fetch(mode) do
39
+ raise ValidationError.new("Unknown ECPay mode: #{mode.inspect}", provider: PROVIDER)
40
+ end, provider: PROVIDER)
41
+ @timeout = timeout
42
+ end
43
+
44
+ # The HashKey and HashIV stay out of logs and consoles.
45
+ def inspect
46
+ "#<#{self.class.name} merchant_id=#{@merchant_id.inspect} mode=#{@mode.inspect} " \
47
+ "base_url=#{@base_url.inspect} hash_key=#{Redaction::FILTERED} hash_iv=#{Redaction::FILTERED}>"
48
+ end
49
+ alias to_s inspect
50
+
51
+ # POST +data+ to +path+ and return the decrypted business payload.
52
+ #
53
+ # @param success_codes [Array<Integer>] extra +RtnCode+s to accept besides +1+
54
+ # @param plain_data [Boolean] the endpoint answers with unencrypted +Data+
55
+ def request(path, data, success_codes: [], plain_data: false)
56
+ envelope = post(path, build_body(data))
57
+ check_transport!(envelope)
58
+
59
+ result = plain_data ? envelope["Data"] : decrypt_data(envelope["Data"])
60
+ check_business!(result, success_codes)
61
+ result
62
+ end
63
+
64
+ private
65
+
66
+ def build_body(data)
67
+ {
68
+ "MerchantID" => @merchant_id,
69
+ "RqHeader" => { "Timestamp" => Time.now.to_i, "Revision" => REVISION },
70
+ # MerchantID is required in the encrypted payload as well as the envelope.
71
+ "Data" => Crypto.encrypt_data(
72
+ { "MerchantID" => @merchant_id }.merge(stringify(data)), @hash_key, @hash_iv
73
+ )
74
+ }
75
+ end
76
+
77
+ # Omit nils rather than sending JSON nulls: an absent optional field is the
78
+ # shape ECPay's own SDKs produce, and the shape these endpoints were verified
79
+ # against. Top-level only — nested payloads are built without nils.
80
+ def stringify(data)
81
+ data.each_with_object({}) do |(key, value), out|
82
+ out[key.to_s] = value unless value.nil?
83
+ end
84
+ end
85
+
86
+ def post(path, body)
87
+ uri = URI("#{@base_url}#{path}")
88
+ http = Net::HTTP.new(uri.host, uri.port)
89
+ http.use_ssl = uri.scheme == "https"
90
+ http.open_timeout = @timeout
91
+ http.read_timeout = @timeout
92
+
93
+ response = nil
94
+ http.request(post_request(uri, body)) { |res| (response = res).read_body }
95
+ check_rate_limit!(response)
96
+ parse_json(response)
97
+ rescue *Error::NETWORK_ERRORS => e
98
+ raise NetworkError.for_failure(e, provider: PROVIDER, name: "ECPay", response: response)
99
+ end
100
+
101
+ # ECPay answers HTTP 403 when a merchant calls too often, and asks it to wait
102
+ # 30 minutes. The caller can retry later.
103
+ def check_rate_limit!(response)
104
+ return unless response.code.to_i == 403
105
+
106
+ raise NetworkError.new("ECPay returned HTTP 403: too many calls, wait 30 minutes",
107
+ provider: PROVIDER, reason: Reason::RATE_LIMITED, raw_code: response.code)
108
+ end
109
+
110
+ def post_request(uri, body)
111
+ request = Net::HTTP::Post.new(uri.request_uri)
112
+ request["Content-Type"] = "application/json"
113
+ request.body = JSON.generate(body)
114
+ request
115
+ end
116
+
117
+ # ECPay answers some errors with HTTP 500 and a normal envelope (a wrong
118
+ # HashKey gives TransCode 110), so the body decides when it can be read.
119
+ # Only a body that is not JSON falls back to the HTTP status.
120
+ # A body that ECPay wrote (a JSON object with +TransCode+) decides the
121
+ # error, whatever the HTTP status. Any other body falls back to the
122
+ # status: HTTP 429 and 5xx are a NetworkError, such as a gateway's own
123
+ # JSON error page (docs/providers/README.md, "The unified model").
124
+ def parse_json(response)
125
+ body = JSON.parse(response.body.to_s)
126
+ unless body.is_a?(Hash) && body.key?("TransCode")
127
+ status_error = NetworkError.for_status(response, provider: PROVIDER)
128
+ raise status_error if status_error
129
+ end
130
+ body
131
+ rescue JSON::ParserError => e
132
+ status_error = NetworkError.for_status(response, provider: PROVIDER)
133
+ raise status_error if status_error
134
+
135
+ raise ProviderError.new(
136
+ "ECPay returned a non-JSON response (HTTP #{response.code})",
137
+ provider: PROVIDER, raw_code: response.code, cause: e
138
+ )
139
+ end
140
+
141
+ # Layer 1 — the envelope. A failure here means the request never reached the
142
+ # business logic (bad credentials, skewed clock, malformed encryption).
143
+ def check_transport!(envelope)
144
+ trans_code = envelope["TransCode"]
145
+ return if trans_code.to_i == 1 && !blank?(envelope["Data"])
146
+
147
+ code, reason = Errors.classify_transport(trans_code)
148
+ message = envelope["TransMsg"].to_s
149
+ raise Einvoice::Error.for(
150
+ code, message.empty? ? "ECPay transport error" : message,
151
+ provider: PROVIDER, reason: reason, raw_code: trans_code.to_s,
152
+ raw_message: message, raw: envelope
153
+ )
154
+ end
155
+
156
+ # Layer 2 — the business result, only reachable once the envelope was good.
157
+ def check_business!(result, success_codes)
158
+ unless result.is_a?(Hash)
159
+ raise ProviderError.new("ECPay returned an unexpected Data payload", provider: PROVIDER,
160
+ raw: result)
161
+ end
162
+
163
+ rtn_code = result["RtnCode"].to_i
164
+ return if rtn_code == 1 || success_codes.include?(rtn_code)
165
+
166
+ message = result["RtnMsg"].to_s
167
+ code, reason = Errors.classify(rtn_code, message)
168
+ raise Einvoice::Error.for(
169
+ code, message.empty? ? "ECPay returned an error" : message,
170
+ provider: PROVIDER, reason: reason, raw_code: rtn_code.to_s,
171
+ raw_message: message, raw: result
172
+ )
173
+ end
174
+
175
+ def decrypt_data(data)
176
+ Crypto.decrypt_data(data, @hash_key, @hash_iv)
177
+ end
178
+
179
+ def blank?(value)
180
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
181
+ end
182
+ end
183
+ end
184
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "json"
5
+
6
+ module Einvoice
7
+ module ECPay
8
+ # The ECPay B2C envelope's +Data+ field is
9
+ # <tt>JSON → PHP urlencode → AES-128-CBC (PKCS7) → Base64</tt>, and the reverse
10
+ # on the way back.
11
+ #
12
+ # The PHP url(en|de)code semantics are the part that trips implementations up:
13
+ # a space is +++ (not +%20+) and +!*'()~+ are percent-encoded, neither of which
14
+ # Ruby's own helpers do (+CGI.escape+ leaves +~+ alone). Encoding is done over
15
+ # bytes so UTF-8 payloads survive.
16
+ #
17
+ # Verified byte-for-byte against ECPay's published cross-language AES vectors
18
+ # (2026-08-15) — see the crypto spec.
19
+ module Crypto
20
+ # PHP +urlencode+ keeps only these unreserved bytes; everything else is %XX.
21
+ UNRESERVED = /[^a-zA-Z0-9\-_.]/n
22
+
23
+ module_function
24
+
25
+ # PHP +urlencode+: space → +++, every other non-unreserved byte → +%XX+.
26
+ def php_url_encode(value)
27
+ value.to_s.b.gsub(UNRESERVED) { |byte| byte == " " ? "+" : format("%%%02X", byte.ord) }
28
+ end
29
+
30
+ # PHP +urldecode+: +++ → space, then percent-decode back to UTF-8.
31
+ def php_url_decode(value)
32
+ value.to_s.tr("+", " ")
33
+ .gsub(/%([0-9A-Fa-f]{2})/) { ::Regexp.last_match(1).hex.chr }
34
+ .force_encoding(Encoding::UTF_8)
35
+ end
36
+
37
+ # AES-128-CBC + PKCS7, Base64-encoded. +key+/+iv+ are the 16-byte HashKey/HashIV.
38
+ def encrypt(plaintext, key, iv)
39
+ cipher = new_cipher(key, iv, :encrypt)
40
+ [cipher.update(plaintext.to_s) + cipher.final].pack("m0")
41
+ end
42
+
43
+ # Reverse of {encrypt}. Raises {Einvoice::ProviderError} on a corrupt payload.
44
+ def decrypt(base64, key, iv)
45
+ cipher = new_cipher(key, iv, :decrypt)
46
+ (cipher.update(base64.to_s.unpack1("m")) + cipher.final).force_encoding(Encoding::UTF_8)
47
+ rescue OpenSSL::Cipher::CipherError, ArgumentError => e
48
+ raise ProviderError.new("Could not decrypt the ECPay response payload",
49
+ provider: "ecpay", cause: e)
50
+ end
51
+
52
+ # Build a request +Data+ value from a payload Hash.
53
+ def encrypt_data(data, key, iv)
54
+ encrypt(php_url_encode(JSON.generate(data)), key, iv)
55
+ end
56
+
57
+ # Read a response +Data+ value back into a Hash.
58
+ def decrypt_data(base64, key, iv)
59
+ JSON.parse(php_url_decode(decrypt(base64, key, iv)))
60
+ rescue JSON::ParserError => e
61
+ raise ProviderError.new("ECPay returned a malformed JSON payload",
62
+ provider: "ecpay", cause: e)
63
+ end
64
+
65
+ # AES-128 needs exactly 16 bytes of key and IV; a merchant pasting the wrong
66
+ # credential is the common cause, so say which one is wrong up front.
67
+ def new_cipher(key, iv, direction)
68
+ assert_length!(key, "hash_key")
69
+ assert_length!(iv, "hash_iv")
70
+ cipher = OpenSSL::Cipher.new("aes-128-cbc").public_send(direction)
71
+ cipher.key = key
72
+ cipher.iv = iv
73
+ cipher
74
+ end
75
+
76
+ def assert_length!(value, field)
77
+ size = value.to_s.bytesize
78
+ return if size == 16
79
+
80
+ raise ValidationError.new("ECPay #{field} must be 16 bytes (AES-128-CBC), got #{size}",
81
+ provider: "ecpay")
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Einvoice
4
+ module ECPay
5
+ # Maps ECPay's two failure channels onto the unified {Einvoice::Error} tree.
6
+ #
7
+ # A B2C response has two independent result fields and both must be checked:
8
+ # the outer +TransCode+ (transport — did the envelope decrypt and parse?) and,
9
+ # after decrypting +Data+, the inner +RtnCode+ (business). Success is the
10
+ # integer +1+ on each.
11
+ #
12
+ # Business codes are the awkward part: they span unrelated ranges (+2+,
13
+ # +1600003+, +5070357+, +5000022+ …) and the same condition can surface under
14
+ # different numbers per endpoint, so the Chinese +RtnMsg+ is the more reliable
15
+ # signal. Classification therefore tries the table of codes confirmed against
16
+ # the live stage API first, then falls back to matching the message.
17
+ module Errors
18
+ # Transport-level codes. 110 was seen live (2026-08-15, stage). 104 and 115
19
+ # come from the shared wire fixtures. Any other code is a ProviderError.
20
+ TRANSPORT = {
21
+ 104 => [:auth, Reason::STALE_TIMESTAMP], # Timestamp is over 10 minutes...
22
+ 110 => [:auth, Reason::CREDENTIALS_INVALID], # The parameter [Data] decrypt fail.
23
+ 115 => [:auth, Reason::NOT_ENROLLED] # B2C/B2B功能尚未開通
24
+ }.freeze
25
+
26
+ # Business codes confirmed by driving the stage API (2026-08-15). Kept small
27
+ # and specific on purpose — a code whose meaning is endpoint-dependent (e.g.
28
+ # a bare +2+) is left to the message matcher instead.
29
+ BUSINESS = {
30
+ 1_600_003 => [:not_found, nil], # 無發票號碼資料
31
+ 2_000_039 => [:not_found, nil], # 查無折讓單資料
32
+ 2_000_042 => [:conflict, Reason::ALLOWANCE_BLOCKED_BY_VOID], # 作廢發票號碼不能折讓
33
+ 2_000_063 => [:conflict, Reason::ALREADY_VOIDED], # 該折讓單已作廢過
34
+ 5_070_357 => [:conflict, Reason::DUPLICATE_ORDER], # 自訂編號重覆
35
+ 5_070_450 => [:conflict, Reason::VOID_BLOCKED_BY_ALLOWANCE], # 該發票已被折讓過
36
+ 5_070_453 => [:conflict, Reason::ALREADY_VOIDED], # 該發票已被作廢過
37
+ 9_000_001 => [:network, nil], # 呼叫財政部API失敗
38
+ # From the shared wire fixtures.
39
+ 4_000_001 => [:not_found, nil], # 不存在此交易單號
40
+ 1_100_040 => [:number_exhausted, nil], # 發票字軌已用完
41
+ 5_070_250 => [:conflict, nil] # 線上折讓已同意,不可作廢
42
+ }.freeze
43
+
44
+ # 財政部 upstream trouble is transient and retryable — never the caller's input.
45
+ UPSTREAM_DOWN = /財政部.*(失敗|維護)|呼叫.*API失敗/
46
+ CREDENTIALS = /金鑰|簽章|未授權/
47
+ NOT_ENROLLED = /特店.*不存在|平台商.*不存在/
48
+ EXHAUSTED = /字軌.*(用罄|用完|不足|已滿)|號碼.*(用罄|用完)/
49
+ # 重複 and 重覆 are both current spellings and ECPay uses both — matching only
50
+ # one silently demotes a duplicate-order conflict to a generic validation error.
51
+ DUPLICATE = /重[複覆]/
52
+ # Two different conflicts that both mention 作廢, and they call for opposite
53
+ # responses. 已作廢 on a void means the invoice already reached the state
54
+ # asked for — safe to treat as success. "作廢…不能…" means the operation was
55
+ # refused *because* the invoice is voided, and nothing happened; treating
56
+ # that as success would record a credit that does not exist.
57
+ # ECPay writes both 已作廢 and 已被作廢; matching only the first meant the
58
+ # fallback missed 5070453's actual wording, which went unnoticed because
59
+ # that code is in the table above.
60
+ ALREADY_VOID = /已(被)?作廢/
61
+ BLOCKED_BY_VOID = /作廢.*不能/
62
+ ALLOWANCE_MADE = /已折讓|折讓過/
63
+ CONFLICTING = /已開立|已存在|同意/
64
+ MISSING = /查無|查不到|無.*資料|不存在/
65
+ BUSY = /系統(錯誤|異常|忙碌)|請稍後/
66
+
67
+ module_function
68
+
69
+ # Classify a transport failure → +[code, reason]+.
70
+ def classify_transport(trans_code)
71
+ TRANSPORT.fetch(trans_code.to_i, [:provider, nil])
72
+ end
73
+
74
+ # Classify a business failure → +[code, reason]+.
75
+ def classify(rtn_code, rtn_msg = "")
76
+ known = BUSINESS[rtn_code.to_i]
77
+ return known if known
78
+
79
+ [message_code(rtn_msg.to_s), message_reason(rtn_msg.to_s)]
80
+ end
81
+
82
+ # The fallback matcher. Anything unrecognized is treated as field/business
83
+ # validation, which is what the long tail of ECPay's codes actually is.
84
+ def message_code(msg)
85
+ case msg
86
+ when UPSTREAM_DOWN then :network
87
+ when CREDENTIALS, NOT_ENROLLED then :auth
88
+ when EXHAUSTED then :number_exhausted
89
+ when DUPLICATE, ALREADY_VOID, BLOCKED_BY_VOID, ALLOWANCE_MADE, CONFLICTING then :conflict
90
+ # AUTH already claimed 特店/平台商不存在 above, so a bare 不存在 here is a
91
+ # missing record rather than an unknown merchant.
92
+ when MISSING then :not_found
93
+ when BUSY then :provider
94
+ else :validation
95
+ end
96
+ end
97
+
98
+ def message_reason(msg)
99
+ case msg
100
+ when CREDENTIALS then Reason::CREDENTIALS_INVALID
101
+ when NOT_ENROLLED then Reason::NOT_ENROLLED
102
+ # Checked before ALREADY_VOID: a message carrying both ("已作廢,不能折讓")
103
+ # is a refusal, and the refusal is the actionable half.
104
+ when BLOCKED_BY_VOID then Reason::ALLOWANCE_BLOCKED_BY_VOID
105
+ when ALREADY_VOID then Reason::ALREADY_VOIDED
106
+ # Only the void API emits 已折讓/折讓過, so it always means "void the
107
+ # allowance first" rather than a plain conflict.
108
+ when ALLOWANCE_MADE then Reason::VOID_BLOCKED_BY_ALLOWANCE
109
+ when DUPLICATE then Reason::DUPLICATE_ORDER
110
+ when BUSY then Reason::RATE_LIMITED
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end