einvoice 1.5.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 +6 -8
  3. data/.github/workflows/build.yml +6 -3
  4. data/CHANGELOG.md +43 -44
  5. data/Gemfile +3 -10
  6. data/README.md +221 -328
  7. data/README.zh-TW.md +322 -0
  8. data/Rakefile +2 -51
  9. data/bin/console +3 -6
  10. data/einvoice.gemspec +16 -18
  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 -13
  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 -9
  49. metadata +52 -145
  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 -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.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
@@ -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