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,183 @@
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, and
25
+ # the stage API accepts a request without it (verified 2026-08-15). It
26
+ # stays until docs/providers/ecpay/b2c.md, open question 1, is settled.
27
+ REVISION = "3.0.0"
28
+
29
+ attr_reader :merchant_id, :mode, :base_url, :timeout
30
+
31
+ def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST,
32
+ base_url: nil, timeout: 30)
33
+ @merchant_id = merchant_id.to_s
34
+ @hash_key = hash_key.to_s
35
+ @hash_iv = hash_iv.to_s
36
+ @mode = mode
37
+ @base_url = Redaction.base_url!(base_url || BASE_URL.fetch(mode) do
38
+ raise ValidationError.new("Unknown ECPay mode: #{mode.inspect}", provider: PROVIDER)
39
+ end, provider: PROVIDER)
40
+ @timeout = timeout
41
+ end
42
+
43
+ # The HashKey and HashIV stay out of logs and consoles.
44
+ def inspect
45
+ "#<#{self.class.name} merchant_id=#{@merchant_id.inspect} mode=#{@mode.inspect} " \
46
+ "base_url=#{@base_url.inspect} hash_key=#{Redaction::FILTERED} hash_iv=#{Redaction::FILTERED}>"
47
+ end
48
+ alias to_s inspect
49
+
50
+ # POST +data+ to +path+ and return the decrypted business payload.
51
+ #
52
+ # @param success_codes [Array<Integer>] extra +RtnCode+s to accept besides +1+
53
+ # @param plain_data [Boolean] the endpoint answers with unencrypted +Data+
54
+ def request(path, data, success_codes: [], plain_data: false)
55
+ envelope = post(path, build_body(data))
56
+ check_transport!(envelope)
57
+
58
+ result = plain_data ? envelope["Data"] : decrypt_data(envelope["Data"])
59
+ check_business!(result, success_codes)
60
+ result
61
+ end
62
+
63
+ private
64
+
65
+ def build_body(data)
66
+ {
67
+ "MerchantID" => @merchant_id,
68
+ "RqHeader" => { "Timestamp" => Time.now.to_i, "Revision" => REVISION },
69
+ # MerchantID is required in the encrypted payload as well as the envelope.
70
+ "Data" => Crypto.encrypt_data(
71
+ { "MerchantID" => @merchant_id }.merge(stringify(data)), @hash_key, @hash_iv
72
+ )
73
+ }
74
+ end
75
+
76
+ # Omit nils rather than sending JSON nulls: an absent optional field is the
77
+ # shape ECPay's own SDKs produce, and the shape these endpoints were verified
78
+ # against. Top-level only — nested payloads are built without nils.
79
+ def stringify(data)
80
+ data.each_with_object({}) do |(key, value), out|
81
+ out[key.to_s] = value unless value.nil?
82
+ end
83
+ end
84
+
85
+ def post(path, body)
86
+ uri = URI("#{@base_url}#{path}")
87
+ http = Net::HTTP.new(uri.host, uri.port)
88
+ http.use_ssl = uri.scheme == "https"
89
+ http.open_timeout = @timeout
90
+ http.read_timeout = @timeout
91
+
92
+ response = nil
93
+ http.request(post_request(uri, body)) { |res| (response = res).read_body }
94
+ check_rate_limit!(response)
95
+ parse_json(response)
96
+ rescue *Error::NETWORK_ERRORS => e
97
+ raise NetworkError.for_failure(e, provider: PROVIDER, name: "ECPay", response: response)
98
+ end
99
+
100
+ # ECPay answers HTTP 403 when a merchant calls too often, and asks it to wait
101
+ # 30 minutes. The caller can retry later.
102
+ def check_rate_limit!(response)
103
+ return unless response.code.to_i == 403
104
+
105
+ raise NetworkError.new("ECPay returned HTTP 403: too many calls, wait 30 minutes",
106
+ provider: PROVIDER, reason: Reason::RATE_LIMITED, raw_code: response.code)
107
+ end
108
+
109
+ def post_request(uri, body)
110
+ request = Net::HTTP::Post.new(uri.request_uri)
111
+ request["Content-Type"] = "application/json"
112
+ request.body = JSON.generate(body)
113
+ request
114
+ end
115
+
116
+ # ECPay answers some errors with HTTP 500 and a normal envelope (a wrong
117
+ # HashKey gives TransCode 110), so the body decides when it can be read.
118
+ # Only a body that is not JSON falls back to the HTTP status.
119
+ # A body that ECPay wrote (a JSON object with +TransCode+) decides the
120
+ # error, whatever the HTTP status. Any other body falls back to the
121
+ # status: HTTP 429 and 5xx are a NetworkError, such as a gateway's own
122
+ # JSON error page (docs/providers/README.md, "The unified model").
123
+ def parse_json(response)
124
+ body = JSON.parse(response.body.to_s)
125
+ unless body.is_a?(Hash) && body.key?("TransCode")
126
+ status_error = NetworkError.for_status(response, provider: PROVIDER)
127
+ raise status_error if status_error
128
+ end
129
+ body
130
+ rescue JSON::ParserError => e
131
+ status_error = NetworkError.for_status(response, provider: PROVIDER)
132
+ raise status_error if status_error
133
+
134
+ raise ProviderError.new(
135
+ "ECPay returned a non-JSON response (HTTP #{response.code})",
136
+ provider: PROVIDER, raw_code: response.code, cause: e
137
+ )
138
+ end
139
+
140
+ # Layer 1 — the envelope. A failure here means the request never reached the
141
+ # business logic (bad credentials, skewed clock, malformed encryption).
142
+ def check_transport!(envelope)
143
+ trans_code = envelope["TransCode"]
144
+ return if trans_code.to_i == 1 && !blank?(envelope["Data"])
145
+
146
+ code, reason = Errors.classify_transport(trans_code)
147
+ message = envelope["TransMsg"].to_s
148
+ raise Einvoice::Error.for(
149
+ code, message.empty? ? "ECPay transport error" : message,
150
+ provider: PROVIDER, reason: reason, raw_code: trans_code.to_s,
151
+ raw_message: message, raw: envelope
152
+ )
153
+ end
154
+
155
+ # Layer 2 — the business result, only reachable once the envelope was good.
156
+ def check_business!(result, success_codes)
157
+ unless result.is_a?(Hash)
158
+ raise ProviderError.new("ECPay returned an unexpected Data payload", provider: PROVIDER,
159
+ raw: result)
160
+ end
161
+
162
+ rtn_code = result["RtnCode"].to_i
163
+ return if rtn_code == 1 || success_codes.include?(rtn_code)
164
+
165
+ message = result["RtnMsg"].to_s
166
+ code, reason = Errors.classify(rtn_code, message)
167
+ raise Einvoice::Error.for(
168
+ code, message.empty? ? "ECPay returned an error" : message,
169
+ provider: PROVIDER, reason: reason, raw_code: rtn_code.to_s,
170
+ raw_message: message, raw: result
171
+ )
172
+ end
173
+
174
+ def decrypt_data(data)
175
+ Crypto.decrypt_data(data, @hash_key, @hash_iv)
176
+ end
177
+
178
+ def blank?(value)
179
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
180
+ end
181
+ end
182
+ end
183
+ 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
@@ -0,0 +1,241 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Einvoice
4
+ module ECPay
5
+ # Maps the unified value model onto ECPay's +Issue+ payload, and checks the
6
+ # field rules locally so a bad request fails before the network.
7
+ #
8
+ # The rules encoded here were confirmed against the live stage API rather than
9
+ # taken from the documentation, which both over-states some requirements the
10
+ # API does not enforce and forbids combinations it accepts (a 統編 invoice may
11
+ # carry a carrier, for instance).
12
+ module Payload
13
+ # 課稅別 → ECPay TaxType. 9 (混合) is derived from the items, not requested.
14
+ TAX_TYPE = {
15
+ TaxType::TAXABLE => "1",
16
+ TaxType::ZERO_RATED => "2",
17
+ TaxType::TAX_FREE => "3",
18
+ TaxType::SPECIAL => "4"
19
+ }.freeze
20
+ MIXED_TAX_CODE = "9"
21
+
22
+ # 載具類別 → ECPay CarrierType.
23
+ CARRIER_TYPE = {
24
+ CarrierType::MEMBER => "1", # 綠界會員載具
25
+ CarrierType::CITIZEN_CERTIFICATE => "2", # 自然人憑證條碼
26
+ CarrierType::MOBILE_BARCODE => "3" # 手機條碼
27
+ }.freeze
28
+
29
+ # ECPay caps 自訂編號 at 50 characters. Input checks the 20-character
30
+ # reason limit, which ECPay shares with the MIG.
31
+ MAX_RELATE_NUMBER_LENGTH = 50
32
+ # Default unit (單位) when an item does not name one; ItemWord is required.
33
+ DEFAULT_UNIT = "式"
34
+
35
+ module_function
36
+
37
+ # Build the +Issue+ Data payload from a parsed {Einvoice::IssueInvoiceInput}.
38
+ def issue(parsed, validate: true)
39
+ options = string_keys(parsed.provider_options)
40
+ carrier = parsed.carrier
41
+ donating = !parsed.donation.nil?
42
+ # A carrier or donated invoice is electronic; anything else prints on paper.
43
+ print = carrier || donating ? "0" : "1"
44
+ b2b = parsed.resolved_category == InvoiceCategory::B2B
45
+
46
+ data = {
47
+ "RelateNumber" => parsed.order_id,
48
+ "CustomerID" => options["customer_id"].to_s,
49
+ "CustomerIdentifier" => b2b ? parsed.buyer&.ubn.to_s : "",
50
+ "CustomerName" => parsed.buyer&.name.to_s,
51
+ "CustomerAddr" => parsed.buyer&.address.to_s,
52
+ "CustomerPhone" => parsed.buyer&.phone.to_s,
53
+ "CustomerEmail" => parsed.buyer&.email.to_s,
54
+ "Print" => print,
55
+ "Donation" => donating ? "1" : "0",
56
+ "LoveCode" => parsed.donation&.npoban.to_s,
57
+ "CarrierType" => carrier ? CARRIER_TYPE.fetch(carrier.type) : "",
58
+ "CarrierNum" => carrier&.code.to_s,
59
+ "TaxType" => tax_type(parsed),
60
+ "SalesAmount" => parsed.amount.total_amount,
61
+ "InvoiceRemark" => parsed.remark.to_s,
62
+ "Items" => items(parsed.items, parsed.tax_type),
63
+ "InvType" => parsed.tax_type == TaxType::SPECIAL ? "08" : "07",
64
+ "vat" => parsed.price_mode == PriceMode::TAX_EXCLUSIVE ? "0" : "1"
65
+ }
66
+ # The core asks for the clearance mark on a zero-rated invoice. ECPay
67
+ # takes the reason from its back office when it is not sent.
68
+ data["ClearanceMark"] = parsed.customs_clearance_mark if parsed.zero_rated?
69
+ data["ZeroTaxRateReason"] = parsed.zero_tax_rate_reason if parsed.zero_rated? && parsed.zero_tax_rate_reason
70
+ # 特種稅額 details the unified model has no field for.
71
+ data["SpecialTaxType"] = options["special_tax_type"] if options.key?("special_tax_type")
72
+ # Last-resort escape hatch for fields this mapper does not model.
73
+ data.merge!(string_keys(options["data"])) if options["data"]
74
+
75
+ validate_issue!(data) if validate
76
+ data
77
+ end
78
+
79
+ # Build the +Items+ array shared by Issue and Allowance.
80
+ def items(list, invoice_tax_type = nil)
81
+ list.each_with_index.map do |item, index|
82
+ row = {
83
+ "ItemSeq" => index + 1,
84
+ "ItemName" => item.description,
85
+ "ItemCount" => item.quantity,
86
+ "ItemWord" => item.unit || DEFAULT_UNIT,
87
+ "ItemPrice" => item.unit_price,
88
+ "ItemTaxType" => TAX_TYPE.fetch(item.tax_type || invoice_tax_type || TaxType::TAXABLE),
89
+ "ItemAmount" => item.amount
90
+ }
91
+ row["ItemRemark"] = item.remark if item.remark
92
+ row
93
+ end
94
+ end
95
+
96
+ # The +Items+ of an Allowance. ECPay wants tax-included prices and amounts,
97
+ # which the core's breakdown has.
98
+ def allowance_items(parsed)
99
+ lines = parsed.tax_breakdown(provider: Client::PROVIDER).lines
100
+ items(parsed.items, parsed.tax_type).zip(lines).map do |row, line|
101
+ row.merge("ItemPrice" => line.gross_unit_price, "ItemTaxType" => TAX_TYPE.fetch(line.tax_type),
102
+ "ItemAmount" => line.gross_amount)
103
+ end
104
+ end
105
+
106
+ # An invoice whose items disagree on 課稅別 is a 混合稅率 (9) invoice; otherwise
107
+ # the invoice-level tax type stands.
108
+ def tax_type(parsed)
109
+ type = TaxType.of(parsed.items, parsed.tax_type)
110
+ type == TaxType::MIXED ? MIXED_TAX_CODE : TAX_TYPE.fetch(type)
111
+ end
112
+
113
+ # Field rules for a built payload. Each was checked against the live API; the
114
+ # RtnCode it would otherwise come back as is noted.
115
+ def validate_issue!(data)
116
+ errors = []
117
+ relate = data["RelateNumber"].to_s
118
+ errors << "RelateNumber is required" if relate.empty?
119
+ # A zero-rated invoice needs ClearanceMark (MIG, 5000007). The adapter
120
+ # sets it, but provider_options[:data] can change the payload after
121
+ # that, so the final payload is checked. A mixed invoice needs it only
122
+ # with a zero-rated item: stage takes taxable plus tax-free without it.
123
+ if zero_rated_payload?(data) && data["ClearanceMark"].to_s.empty?
124
+ errors << "ClearanceMark is required for a zero-rated item"
125
+ end
126
+
127
+ # 發票金額(含稅) must equal round(Σ ItemAmount) — 5000022. Only checked for
128
+ # 含稅 (vat=1). With vat=0, ECPay does not read ItemAmount: it stores
129
+ # ItemPrice × 1.05 and checks SalesAmount against that (stage, 2026-11-15).
130
+ if data["vat"] != "0"
131
+ total = data["Items"].sum { |item| item["ItemAmount"].to_f }
132
+ unless total.round == data["SalesAmount"]
133
+ errors << "SalesAmount (#{data['SalesAmount']}) must equal the item total (#{total.round})"
134
+ end
135
+ end
136
+
137
+ errors.concat(buyer_errors(data))
138
+ errors.concat(carrier_errors(data))
139
+
140
+ unless errors.empty?
141
+ raise ValidationError.new("Invalid ECPay invoice payload — #{errors.join('; ')}",
142
+ provider: Client::PROVIDER, raw_message: errors.join("; "))
143
+ end
144
+
145
+ limits = own_limits(data)
146
+ return if limits.empty?
147
+
148
+ raise UnsupportedError.new("ECPay does not take this invoice — #{limits.join('; ')}",
149
+ provider: Client::PROVIDER, raw_message: limits.join("; "))
150
+ end
151
+
152
+ def zero_rated_payload?(data)
153
+ zero = TAX_TYPE.fetch(TaxType::ZERO_RATED)
154
+ return true if data["TaxType"] == zero
155
+
156
+ data["TaxType"] == MIXED_TAX_CODE && Array(data["Items"]).any? { |item| item["ItemTaxType"] == zero }
157
+ end
158
+
159
+ def buyer_errors(data)
160
+ errors = []
161
+ ubn = data["CustomerIdentifier"].to_s
162
+ errors << "CustomerIdentifier must be 8 digits" unless ubn.empty? || ubn.match?(/\A\d{8}\z/)
163
+
164
+ # Input enforces the same rule, so this only fires for a Donation value
165
+ # object built directly, which Input passes through untouched.
166
+ love_code = data["LoveCode"].to_s
167
+ if data["Donation"] == "1" && !love_code.match?(Donation::CODE_FORMAT)
168
+ errors << "LoveCode (3–7 digits) is required when donating"
169
+ end
170
+
171
+ errors
172
+ end
173
+
174
+ def carrier_errors(data)
175
+ errors = []
176
+ carrier = data["CarrierType"].to_s
177
+ # A B2C carrier invoice is electronic and cannot also print — 5000015.
178
+ if data["CustomerIdentifier"].to_s.empty? && !carrier.empty? && data["Print"] == "1"
179
+ errors << "Print must be 0 for a carrier invoice"
180
+ end
181
+ errors
182
+ end
183
+
184
+ # ECPay's own rules, beyond the MIG. The MIG allows these invoices, so
185
+ # they are UnsupportedError (docs/providers/README.md, "The unified
186
+ # model"): another provider may take them.
187
+ def own_limits(data)
188
+ limits = []
189
+ # The MIG has no order id, so this limit is ECPay's own.
190
+ if data["RelateNumber"].to_s.length > MAX_RELATE_NUMBER_LENGTH
191
+ limits << "RelateNumber must be #{MAX_RELATE_NUMBER_LENGTH} characters or fewer"
192
+ end
193
+ # A printed invoice needs somewhere to print to, and a way to notify.
194
+ if data["Print"] == "1"
195
+ limits << "CustomerName is required for a printed invoice" if data["CustomerName"].to_s.empty?
196
+ limits << "CustomerAddr is required for a printed invoice" if data["CustomerAddr"].to_s.empty?
197
+ if data["CustomerEmail"].to_s.empty? && data["CustomerPhone"].to_s.empty?
198
+ limits << "CustomerEmail or CustomerPhone is required for a printed invoice"
199
+ end
200
+ end
201
+ # A 統編 invoice that is not printed has to live in a carrier — 5000028.
202
+ if !data["CustomerIdentifier"].to_s.empty? && data["Print"] == "0" && data["CarrierType"].to_s.empty?
203
+ limits << "A non-printed B2B invoice must use a carrier"
204
+ end
205
+ limits
206
+ end
207
+
208
+ # The sum of ItemAmount has to equal AllowanceAmount [doc 7901]: the
209
+ # totals must agree, as the MIG asks. On each item ItemPrice × ItemCount
210
+ # may differ from ItemAmount by 1 at most. That is ECPay's own rule, so
211
+ # it is an UnsupportedError (docs/providers/README.md, "The unified
212
+ # model").
213
+ def check_allowance!(data)
214
+ total = data["Items"].sum { |item| item["ItemAmount"].to_r }
215
+ unless total.round == data["AllowanceAmount"]
216
+ raise ValidationError.new("Invalid ECPay allowance payload — AllowanceAmount " \
217
+ "(#{data['AllowanceAmount']}) must equal the item total (#{total.round})",
218
+ provider: Client::PROVIDER)
219
+ end
220
+
221
+ gaps = data["Items"].each_with_index.filter_map do |item, index|
222
+ product = item["ItemPrice"].to_r * item["ItemCount"].to_r
223
+ next if (product - item["ItemAmount"].to_r).abs <= 1
224
+
225
+ "Items[#{index}]: ItemPrice × ItemCount (#{Number.plain(product)}) must be within 1 of " \
226
+ "ItemAmount (#{item['ItemAmount']})"
227
+ end
228
+ return if gaps.empty?
229
+
230
+ raise UnsupportedError.new("ECPay does not take this allowance — #{gaps.join('; ')}",
231
+ provider: Client::PROVIDER)
232
+ end
233
+
234
+ def string_keys(hash)
235
+ return {} unless hash.is_a?(Hash)
236
+
237
+ hash.each_with_object({}) { |(key, value), out| out[key.to_s] = value }
238
+ end
239
+ end
240
+ end
241
+ end