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,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),
63
+ "InvType" => parsed.resolved_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?
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(parsed)
81
+ parsed.items.zip(parsed.item_tax_types).each_with_index.map do |(item, type), 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(type),
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.lines
100
+ items(parsed).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 = parsed.resolved_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
@@ -0,0 +1,371 @@
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
+ # IIS_Tax_Type in a GetIssue result. 9 is mixed.
35
+ INVOICE_TAX_TYPE = TAX_CODE_TO_TYPE.merge(Payload::MIXED_TAX_CODE => TaxType::MIXED).freeze
36
+ # The only rate ECPay applies to a taxable line.
37
+ TAXABLE_RATE = Rational(5, 100)
38
+
39
+ attr_reader :capabilities, :client
40
+
41
+ # @param merchant_id [String] 特店編號
42
+ # @param hash_key [String] 16-byte AES HashKey — server-side only
43
+ # @param hash_iv [String] 16-byte AES HashIV — server-side only
44
+ # @param mode [Symbol] +:test+ (stage) or +:production+
45
+ # @param base_url [String, nil] override the host, e.g. in tests
46
+ # @param timeout [Integer] open/read timeout in seconds
47
+ # @param validate_payload [Boolean] check field rules locally before sending
48
+ def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST,
49
+ base_url: nil, timeout: 30, validate_payload: true)
50
+ super()
51
+ @client = Client.new(merchant_id: merchant_id, hash_key: hash_key, hash_iv: hash_iv,
52
+ mode: mode, base_url: base_url, timeout: timeout)
53
+ @validate_payload = validate_payload
54
+ @capabilities = CAPABILITIES
55
+ end
56
+
57
+ def name
58
+ Client::PROVIDER
59
+ end
60
+
61
+ # Call any B2C endpoint with a raw Data payload — the envelope, encryption
62
+ # and error mapping are applied as usual:
63
+ #
64
+ # provider.raw("/B2CInvoice/InvoicePrint", { "InvoiceNo" => "LA25000001" })
65
+ #
66
+ # Brace the payload: an unbraced hash would be read as this method's own
67
+ # keyword arguments.
68
+ def raw(path, data, success_codes: [], plain_data: false)
69
+ @client.request(path, data, success_codes: success_codes, plain_data: plain_data)
70
+ end
71
+
72
+ # 開立發票.
73
+ def issue(input)
74
+ parsed = Input.issue(input, provider: name)
75
+ assert_currency_supported!(parsed.currency)
76
+ assert_rate_supported!(parsed)
77
+ data = Payload.issue(parsed, validate: @validate_payload)
78
+ result = @client.request("/B2CInvoice/Issue", data)
79
+
80
+ IssueInvoiceResult.new(
81
+ invoice_number: result["InvoiceNo"].to_s,
82
+ invoice_datetime: parse_time(result["InvoiceDate"]),
83
+ random_code: result["RandomNumber"].to_s,
84
+ order_id: parsed.order_id,
85
+ total_amount: parsed.amount.total_amount,
86
+ buyer_ubn: parsed.buyer&.ubn,
87
+ tax_type: parsed.resolved_tax_type,
88
+ tax_rate: parsed.tax_rate,
89
+ status: InvoiceStatus::ISSUED,
90
+ raw: result
91
+ )
92
+ end
93
+
94
+ # 作廢發票. ECPay keys the void on the invoice's issue date, so the reference
95
+ # needs invoice_datetime, or an order_id to look it up (see invoice_date).
96
+ #
97
+ # An invoice with a live 折讓 cannot be voided (+:void_blocked_by_allowance+);
98
+ # void the allowance first.
99
+ def void(input)
100
+ parsed = Input.void(input, provider: name)
101
+
102
+ result = @client.request("/B2CInvoice/Invalid", {
103
+ "InvoiceNo" => parsed.invoice.number,
104
+ "InvoiceDate" => invoice_date(parsed.invoice, "void"),
105
+ "Reason" => parsed.reason
106
+ })
107
+ VoidInvoiceResult.new(invoice_number: parsed.invoice.number,
108
+ status: InvoiceStatus::VOIDED, raw: result)
109
+ end
110
+
111
+ # 開立折讓 (紙本). Returns the 折讓單號 immediately; it can be voided right away.
112
+ # Defaults to notifying nobody — pass
113
+ # <tt>provider_options: { allowance_notify: "E", notify_mail: "..." }</tt> to
114
+ # have ECPay tell the buyer (S 簡訊 / E 信箱 / A 兩者 / N 不通知).
115
+ def allowance(input)
116
+ parsed = Input.allowance(input, provider: name)
117
+ assert_rate_supported!(parsed)
118
+ options = Payload.string_keys(parsed.provider_options)
119
+
120
+ data = {
121
+ "InvoiceNo" => parsed.invoice.number,
122
+ "AllowanceNotify" => options["allowance_notify"] || "N",
123
+ "CustomerName" => options["customer_name"],
124
+ "NotifyMail" => options["notify_mail"],
125
+ "NotifyPhone" => options["notify_phone"],
126
+ "AllowanceAmount" => parsed.amount.total_amount,
127
+ "Reason" => options["reason"],
128
+ "Items" => Payload.allowance_items(parsed)
129
+ }.compact
130
+ Payload.check_allowance!(data) if @validate_payload
131
+ data["InvoiceDate"] = invoice_date(parsed.invoice, "allowance")
132
+ result = @client.request("/B2CInvoice/Allowance", data)
133
+
134
+ AllowanceResult.new(
135
+ allowance_number: result["IA_Allow_No"].to_s,
136
+ invoice_number: result["IA_Invoice_No"] || parsed.invoice.number,
137
+ allowance_date: parse_time(result["IA_Date"])&.to_date,
138
+ total_amount: parsed.amount.total_amount,
139
+ raw: result
140
+ )
141
+ end
142
+
143
+ # 作廢折讓. Voids one 折讓單, not the invoice. ECPay needs the invoice number
144
+ # too, so a plain allowance number is not enough.
145
+ def void_allowance(input)
146
+ parsed = Input.void_allowance(input, provider: name)
147
+ allowance = parsed.allowance
148
+ if allowance.invoice_number.nil?
149
+ raise ValidationError.new("void_allowance needs allowance.invoice_number", provider: name)
150
+ end
151
+
152
+ result = @client.request("/B2CInvoice/AllowanceInvalid", {
153
+ "InvoiceNo" => allowance.invoice_number,
154
+ "AllowanceNo" => allowance.allowance_number,
155
+ "Reason" => parsed.reason
156
+ })
157
+ VoidAllowanceResult.new(allowance_number: allowance.allowance_number, raw: result)
158
+ end
159
+
160
+ # 查詢發票. By invoice number when the reference has the number and the
161
+ # issue date, which ECPay pairs with it. Otherwise by 自訂編號. A query by
162
+ # 自訂編號 for a reference with a number checks that ECPay found that
163
+ # number, as an order id may belong to another invoice.
164
+ def query(input)
165
+ reference = Input.query(input, provider: name).invoice
166
+ if reference.order_id && (reference.number.nil? || reference.invoice_datetime.nil?)
167
+ assert_supports!(Capability::QUERY_BY_ORDER_ID)
168
+ return query_by_order_id(reference.order_id, number: reference.number)
169
+ end
170
+
171
+ if reference.invoice_datetime.nil?
172
+ raise ValidationError.new("query by number needs invoice.invoice_datetime", provider: name)
173
+ end
174
+
175
+ result = @client.request("/B2CInvoice/GetIssue", {
176
+ "InvoiceNo" => reference.number,
177
+ "InvoiceDate" => format_date(reference.invoice_datetime)
178
+ })
179
+ build_query_result(result, reference)
180
+ end
181
+
182
+ # Whether a carrier is registered. ECPay can check a 手機條碼 only.
183
+ def validate_carrier(carrier)
184
+ parsed = Input.carrier(carrier, provider: name)
185
+ unless parsed.type == CarrierType::MOBILE_BARCODE
186
+ raise UnsupportedError.new("ECPay can check a mobile barcode only, not #{parsed.type}", provider: name)
187
+ end
188
+
189
+ @client.request("/B2CInvoice/CheckBarcode", { "BarCode" => parsed.code })["IsExist"] == "Y"
190
+ end
191
+
192
+ # 愛心碼驗證 — whether a donation code is registered.
193
+ def validate_love_code(love_code)
194
+ !love_code_organ_name(love_code).nil?
195
+ end
196
+
197
+ # The receiving organisation's name for a 愛心碼, or +nil+ when unregistered.
198
+ def love_code_organ_name(love_code)
199
+ if @validate_payload && !love_code.to_s.match?(Donation::CODE_FORMAT)
200
+ raise ValidationError.new("Invalid love code: #{love_code.inspect}", provider: name)
201
+ end
202
+
203
+ result = @client.request("/B2CInvoice/CheckLoveCode", { "LoveCode" => love_code })
204
+ return nil unless result["IsExist"] == "Y"
205
+
206
+ name = result["OrganName"].to_s
207
+ name.empty? ? nil : name
208
+ end
209
+
210
+ private
211
+
212
+ # ECPay fixes the rate by TaxType. A taxable line is always 5%.
213
+ def assert_rate_supported!(parsed)
214
+ taxable = parsed.item_tax_types.include?(TaxType::TAXABLE)
215
+ return unless taxable && parsed.tax_rate != TAXABLE_RATE
216
+
217
+ raise UnsupportedError.new("ECPay taxes a taxable invoice at 0.05 only, got #{parsed.tax_rate.to_f}",
218
+ provider: name)
219
+ end
220
+
221
+ # GetIssue always sends both totals [doc 7923] [live], so a missing one is
222
+ # an error. So is a value that is not a whole number.
223
+ def build_query_result(result, reference)
224
+ total = amount!(result, "IIS_Sales_Amount")
225
+ tax = amount!(result, "IIS_Tax_Amount")
226
+ tax_type = INVOICE_TAX_TYPE[result["IIS_Tax_Type"].to_s]
227
+ items = TaxType.fill_items(build_items(result["Items"]), tax_type)
228
+
229
+ QueryInvoiceResult.new(
230
+ invoice_number: result["IIS_Number"] || reference.number.to_s,
231
+ invoice_datetime: parse_time(result["IIS_Create_Date"]),
232
+ random_code: result["IIS_Random_Number"].to_s,
233
+ order_id: result["IIS_Relate_Number"] || reference.order_id,
234
+ status: derive_status(result),
235
+ amount: AmountSummary.new(sales_amount: total - tax, tax_amount: tax,
236
+ total_amount: total),
237
+ buyer: build_buyer(result),
238
+ items: items,
239
+ tax_type: tax_type,
240
+ tax_rate: query_rate(tax_type, result["IIS_Tax_Rate"]),
241
+ raw: result
242
+ )
243
+ end
244
+
245
+ # ECPay fixes the rate of a taxable, zero-rated or tax-free invoice. A
246
+ # mixed-tax invoice always has a taxable line [doc 7896]. A special-tax
247
+ # invoice has its own rate, which GetIssue returns. A rate that is not a
248
+ # MIG rate reads as nil, so an allowance has to give one.
249
+ def query_rate(tax_type, reported)
250
+ case tax_type
251
+ when TaxType::TAXABLE, TaxType::MIXED then TAXABLE_RATE
252
+ when TaxType::ZERO_RATED, TaxType::TAX_FREE then 0r
253
+ when TaxType::SPECIAL
254
+ begin
255
+ Input.mig_rate!(reported, "IIS_Tax_Rate", name)
256
+ rescue ValidationError
257
+ nil
258
+ end
259
+ end
260
+ end
261
+
262
+ def build_buyer(result)
263
+ Buyer.new(
264
+ name: presence(result["IIS_Customer_Name"]),
265
+ # ECPay fills a B2C invoice's 統編 with a zero placeholder.
266
+ ubn: presence(result["IIS_Identifier"], placeholder: "0000000000"),
267
+ email: presence(result["IIS_Customer_Email"]),
268
+ address: presence(result["IIS_Customer_Addr"]),
269
+ phone: presence(result["IIS_Customer_Phone"])
270
+ )
271
+ end
272
+
273
+ def build_items(rows)
274
+ Array(rows).map do |row|
275
+ InvoiceItem.new(
276
+ description: row["ItemName"].to_s,
277
+ quantity: item_number(row, "ItemCount"),
278
+ unit_price: item_number(row, "ItemPrice"),
279
+ amount: item_number(row, "ItemAmount"),
280
+ unit: presence(row["ItemWord"]),
281
+ tax_type: TAX_CODE_TO_TYPE[row["ItemTaxType"].to_s],
282
+ remark: presence(row["ItemRemark"])
283
+ )
284
+ end
285
+ end
286
+
287
+ # ECPay reports the lifecycle across two fields: an explicit void flag, and
288
+ # the remaining creditable amount falling below the sales total once a 折讓
289
+ # exists.
290
+ def derive_status(result)
291
+ # 註銷 (cancelled) has no unified status.
292
+ return nil if result["IIS_Issue_Status"].to_s == "0"
293
+ return InvoiceStatus::VOIDED if result["IIS_Invalid_Status"].to_s == "1"
294
+
295
+ sales = amount!(result, "IIS_Sales_Amount")
296
+ remaining = amount!(result, "IIS_Remain_Allowance_Amt")
297
+ return InvoiceStatus::ALLOWANCE if sales.positive? && remaining < sales
298
+
299
+ InvoiceStatus::ISSUED
300
+ end
301
+
302
+ def amount!(result, field)
303
+ Number.response_integer!(result[field], field: field, provider: name, raw: result)
304
+ end
305
+
306
+ # ECPay returns item numbers as JSON numbers, such as 2.0. A missing one
307
+ # is nil, not 0.
308
+ def item_number(row, field)
309
+ Number.response_plain(row[field], field: "Items #{field}", provider: name, raw: row)
310
+ end
311
+
312
+ def presence(value, placeholder: nil)
313
+ string = value.to_s
314
+ string.empty? || string == placeholder ? nil : string
315
+ end
316
+
317
+ # "2026-08-15 23:02:23" (Asia/Taipei) → Time. Falls back to nil so a missing
318
+ # date never masquerades as "now".
319
+ def parse_time(value)
320
+ match = /\A(\d{4})[-\/](\d{2})[-\/](\d{2})(?:[ T](\d{2}):(\d{2}):(\d{2}))?/.match(value.to_s.strip)
321
+ return nil unless match
322
+
323
+ year, month, day, hour, minute, second = match.captures
324
+ Time.new(year.to_i, month.to_i, day.to_i, hour.to_i, minute.to_i, second.to_i, "+08:00")
325
+ end
326
+
327
+ # +number+, when given, is the invoice the caller means. ECPay returns
328
+ # the invoice that has the order id now, so a different number is an
329
+ # error, not a result.
330
+ def query_by_order_id(order_id, number: nil)
331
+ result = @client.request("/B2CInvoice/GetIssue", { "RelateNumber" => order_id })
332
+ found = build_query_result(result, InvoiceReference.new(order_id: order_id))
333
+ if number && found.invoice_number != number
334
+ raise ProviderError.new("ECPay found invoice #{found.invoice_number} for order id #{order_id}, " \
335
+ "not #{number}", provider: name, raw: result)
336
+ end
337
+ found
338
+ end
339
+
340
+ # The issue date that Invalid, Allowance and GetIssue ask for. Taken from the
341
+ # reference, else looked up by order id. A failed lookup is the provider's
342
+ # error, not the invoice's: a NotFoundError would read as "the invoice of
343
+ # this call does not exist".
344
+ def invoice_date(reference, operation)
345
+ return format_date(reference.invoice_datetime) if reference.invoice_datetime
346
+
347
+ if reference.order_id.nil?
348
+ raise ValidationError.new("#{operation} needs invoice.invoice_datetime, or invoice.order_id to look it up",
349
+ provider: name)
350
+ end
351
+
352
+ found = begin
353
+ query_by_order_id(reference.order_id, number: reference.number)
354
+ rescue Error => e
355
+ raise ProviderError.new("#{operation} needs invoice.invoice_datetime; looking it up by order id failed: " \
356
+ "#{e.message}", provider: name, reason: Reason::LOOKUP_FAILED, cause: e)
357
+ end
358
+ if found.invoice_datetime.nil?
359
+ raise ProviderError.new("#{operation} needs invoice.invoice_datetime; the invoice found by order id has " \
360
+ "no issue date", provider: name, reason: Reason::LOOKUP_FAILED)
361
+ end
362
+ format_date(found.invoice_datetime)
363
+ end
364
+
365
+ # ECPay dates are Taipei-local.
366
+ def format_date(time)
367
+ Taipei.date(time, provider: name).strftime("%Y-%m-%d")
368
+ end
369
+ end
370
+ end
371
+ 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