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.
- checksums.yaml +4 -4
- data/.coderabbit.yaml +6 -8
- data/.github/workflows/build.yml +6 -3
- data/.github/workflows/cron.yml +4 -2
- data/CHANGELOG.md +63 -44
- data/Gemfile +3 -10
- data/README.md +284 -325
- data/README.zh-TW.md +381 -0
- data/Rakefile +2 -51
- data/bin/console +3 -6
- data/einvoice.gemspec +17 -18
- data/lib/einvoice/amego/client.rb +116 -0
- data/lib/einvoice/amego/errors.rb +84 -0
- data/lib/einvoice/amego/payload.rb +270 -0
- data/lib/einvoice/amego/provider.rb +272 -0
- data/lib/einvoice/amego.rb +27 -0
- data/lib/einvoice/capability.rb +79 -0
- data/lib/einvoice/ecpay/client.rb +184 -0
- data/lib/einvoice/ecpay/crypto.rb +85 -0
- data/lib/einvoice/ecpay/errors.rb +115 -0
- data/lib/einvoice/ecpay/payload.rb +241 -0
- data/lib/einvoice/ecpay/provider.rb +371 -0
- data/lib/einvoice/ecpay.rb +31 -0
- data/lib/einvoice/error.rb +220 -0
- data/lib/einvoice/ezpay/client.rb +130 -0
- data/lib/einvoice/ezpay/crypto.rb +85 -0
- data/lib/einvoice/ezpay/errors.rb +72 -0
- data/lib/einvoice/ezpay/payload.rb +269 -0
- data/lib/einvoice/ezpay/provider.rb +253 -0
- data/lib/einvoice/ezpay.rb +19 -0
- data/lib/einvoice/input.rb +547 -0
- data/lib/einvoice/mock_provider.rb +191 -0
- data/lib/einvoice/mof/donation_codes.rb +157 -0
- data/lib/einvoice/mof.rb +16 -0
- data/lib/einvoice/number.rb +91 -0
- data/lib/einvoice/provider.rb +57 -13
- data/lib/einvoice/redaction.rb +54 -0
- data/lib/einvoice/taipei.rb +89 -0
- data/lib/einvoice/tax_split.rb +112 -0
- data/lib/einvoice/tradevan/default_api/client.rb +175 -0
- data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
- data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
- data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
- data/lib/einvoice/tradevan/default_api/provider.rb +353 -0
- data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
- data/lib/einvoice/tradevan.rb +25 -0
- data/lib/einvoice/types.rb +365 -0
- data/lib/einvoice/version.rb +3 -1
- data/lib/einvoice.rb +21 -9
- metadata +52 -144
- data/docs/Tradevan E-Invoice APIs.md +0 -201
- data/docs/neweb.md +0 -347
- data/lib/einvoice/client.rb +0 -21
- data/lib/einvoice/configuration.rb +0 -49
- data/lib/einvoice/connection.rb +0 -31
- data/lib/einvoice/donation_unit_list.json +0 -2025
- data/lib/einvoice/result.rb +0 -21
- data/lib/einvoice/tradevan/model/base.rb +0 -34
- data/lib/einvoice/tradevan/model/issue_data.rb +0 -129
- data/lib/einvoice/tradevan/model/issue_item.rb +0 -41
- data/lib/einvoice/tradevan/model/void_data.rb +0 -35
- data/lib/einvoice/tradevan/provider.rb +0 -139
- data/lib/einvoice/tradevan/result.rb +0 -25
- data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
- data/lib/faraday/response/decode_tradevan.rb +0 -37
- data/lib/faraday/response/parse_xml.rb +0 -14
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module EzPay
|
|
5
|
+
# Maps the unified value model onto ezPay's payload fields, and checks the
|
|
6
|
+
# rules from docs/providers/ezpay/invoice.md locally, so a bad request fails
|
|
7
|
+
# before the network.
|
|
8
|
+
module Payload
|
|
9
|
+
TAX_TYPE = {
|
|
10
|
+
TaxType::TAXABLE => "1",
|
|
11
|
+
TaxType::ZERO_RATED => "2",
|
|
12
|
+
TaxType::TAX_FREE => "3"
|
|
13
|
+
}.freeze
|
|
14
|
+
MIXED_TAX_CODE = "9"
|
|
15
|
+
|
|
16
|
+
CARRIER_TYPE = {
|
|
17
|
+
CarrierType::MOBILE_BARCODE => "0",
|
|
18
|
+
CarrierType::CITIZEN_CERTIFICATE => "1",
|
|
19
|
+
CarrierType::MEMBER => "2" # ezPay's own member carrier
|
|
20
|
+
}.freeze
|
|
21
|
+
|
|
22
|
+
CONSUMER_NAME = "消費者"
|
|
23
|
+
DEFAULT_UNIT = "個"
|
|
24
|
+
VOID_ALLOWANCE_REASON = "作廢折讓"
|
|
25
|
+
# The rates TaxRate takes, as a percent (docs, section 4.2).
|
|
26
|
+
TAX_RATES = { 0r => "0", Rational(5, 100) => "5" }.freeze
|
|
27
|
+
ITEM_SEPARATOR = "|"
|
|
28
|
+
ORDER_ID = /\A[A-Za-z0-9_]{1,20}\z/
|
|
29
|
+
|
|
30
|
+
# [limit when the text is all ASCII, limit when it is not]
|
|
31
|
+
UNIT_LIMIT = [6, 2].freeze
|
|
32
|
+
REASON_LIMIT = [20, 6].freeze
|
|
33
|
+
|
|
34
|
+
module_function
|
|
35
|
+
|
|
36
|
+
# +invoice_issue+ fields from a parsed {IssueInvoiceInput}.
|
|
37
|
+
def issue(parsed)
|
|
38
|
+
b2b = parsed.resolved_category == InvoiceCategory::B2B
|
|
39
|
+
options = string_keys(parsed.provider_options)
|
|
40
|
+
types = parsed.item_tax_types
|
|
41
|
+
mixed = types.uniq.size > 1
|
|
42
|
+
check_issue!(parsed, b2b, types, mixed)
|
|
43
|
+
|
|
44
|
+
breakdown = parsed.tax_breakdown
|
|
45
|
+
|
|
46
|
+
fields = {
|
|
47
|
+
"MerchantOrderNo" => parsed.order_id.to_s,
|
|
48
|
+
"Status" => "1",
|
|
49
|
+
"Category" => b2b ? "B2B" : "B2C",
|
|
50
|
+
"BuyerName" => buyer_name(parsed.buyer, b2b),
|
|
51
|
+
"BuyerUBN" => b2b ? parsed.buyer.ubn.to_s : "",
|
|
52
|
+
"BuyerAddress" => parsed.buyer&.address.to_s,
|
|
53
|
+
"BuyerEmail" => parsed.buyer&.email.to_s,
|
|
54
|
+
**carrier_fields(parsed.carrier, parsed.buyer),
|
|
55
|
+
"LoveCode" => parsed.donation&.npoban.to_s,
|
|
56
|
+
"PrintFlag" => b2b || (parsed.carrier.nil? && parsed.donation.nil?) ? "Y" : "N",
|
|
57
|
+
"TaxType" => mixed ? MIXED_TAX_CODE : TAX_TYPE.fetch(types.first),
|
|
58
|
+
"TaxRate" => TAX_RATES.fetch(parsed.tax_rate)
|
|
59
|
+
}
|
|
60
|
+
# ezPay has no field for zero_tax_rate_reason (docs, section 4.6).
|
|
61
|
+
fields["CustomsClearance"] = parsed.customs_clearance_mark if parsed.zero_rated?
|
|
62
|
+
fields.merge!(issue_amounts(breakdown, mixed))
|
|
63
|
+
fields.merge!(item_fields(parsed.items, breakdown.lines, net: b2b))
|
|
64
|
+
fields["ItemTaxType"] = types.map { |type| TAX_TYPE.fetch(type) }.join(ITEM_SEPARATOR) if mixed
|
|
65
|
+
fields["Comment"] = parsed.remark.to_s
|
|
66
|
+
fields
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# +invoice_invalid+ fields.
|
|
70
|
+
def void(parsed)
|
|
71
|
+
{ "InvoiceNumber" => parsed.invoice.number.to_s, "InvalidReason" => reason!(parsed.reason) }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# +allowance_issue+ fields. Confirmed at once (+Status+ 1). +original+
|
|
75
|
+
# has the invoice's +order_id+, and +business+ says if its buyer has a
|
|
76
|
+
# 統一編號 (section 4.3).
|
|
77
|
+
def allowance(parsed, original)
|
|
78
|
+
options = string_keys(parsed.provider_options)
|
|
79
|
+
check_rate!(parsed.tax_rate)
|
|
80
|
+
breakdown = parsed.tax_breakdown
|
|
81
|
+
refuse_special!(breakdown.lines.map(&:tax_type))
|
|
82
|
+
|
|
83
|
+
fields = { "InvoiceNo" => parsed.invoice.number.to_s, "MerchantOrderNo" => original[:order_id].to_s }
|
|
84
|
+
fields.merge!(item_fields(parsed.items, breakdown.lines, net: original[:business]))
|
|
85
|
+
fields["ItemTaxAmt"] = breakdown.lines.map { |line| original[:business] ? line.tax : 0 }.join(ITEM_SEPARATOR)
|
|
86
|
+
fields["TotalAmt"] = parsed.amount.total_amount
|
|
87
|
+
fields["TaxTypeForMixed"] = options["tax_type_for_mixed"].to_s if options.key?("tax_type_for_mixed")
|
|
88
|
+
fields["BuyerEmail"] = options["buyer_email"].to_s if options.key?("buyer_email")
|
|
89
|
+
fields["Status"] = "1"
|
|
90
|
+
fields
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# +allowanceInvalid+ fields.
|
|
94
|
+
def void_allowance(parsed)
|
|
95
|
+
{ "AllowanceNo" => parsed.allowance.allowance_number.to_s,
|
|
96
|
+
"InvalidReason" => reason!(parsed.reason || VOID_ALLOWANCE_REASON) }
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# +invoice_search+ fields, by number. ezPay needs the random code with
|
|
100
|
+
# it. A query by order id needs the total, so the adapter does not offer
|
|
101
|
+
# it (section 4.6).
|
|
102
|
+
def query(reference)
|
|
103
|
+
invalid!("an ezPay query needs invoice.random_code with the number") unless queryable?(reference)
|
|
104
|
+
|
|
105
|
+
{ "SearchType" => "0", "InvoiceNumber" => reference.number.to_s, "RandomNum" => reference.random_code.to_s }
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Whether +reference+ has the two keys of a query by number.
|
|
109
|
+
def queryable?(reference)
|
|
110
|
+
!reference.number.nil? && !reference.random_code.nil?
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# --- issue -------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
def check_issue!(parsed, b2b, types, mixed)
|
|
116
|
+
unless parsed.order_id.to_s.match?(ORDER_ID)
|
|
117
|
+
unsupported!("ezPay takes an order_id of 1 to 20 letters, digits or _")
|
|
118
|
+
end
|
|
119
|
+
max!(parsed.buyer&.email.to_s, 50, "buyer email")
|
|
120
|
+
refuse_special!(types)
|
|
121
|
+
unsupported!("ezPay allows mixed tax only on a B2C invoice") if mixed && b2b
|
|
122
|
+
# The MIG allows a carrier and a donation on a B2B invoice, and a carrier
|
|
123
|
+
# with a donation. ezPay refuses all three.
|
|
124
|
+
unsupported!("ezPay takes a donation only on a B2C invoice") if b2b && parsed.donation
|
|
125
|
+
unsupported!("ezPay takes a carrier only on a B2C invoice") if b2b && parsed.carrier
|
|
126
|
+
unsupported!("ezPay does not take a carrier together with a donation") if parsed.carrier && parsed.donation
|
|
127
|
+
check_rate!(parsed.tax_rate)
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def refuse_special!(types)
|
|
131
|
+
return unless types.include?(TaxType::SPECIAL)
|
|
132
|
+
|
|
133
|
+
raise UnsupportedError.new("ezPay adapter does not support special tax (特種稅額)", provider: Client::PROVIDER)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# The core has checked that +rate+ is a MIG rate. ezPay takes two of them.
|
|
137
|
+
def check_rate!(rate)
|
|
138
|
+
return if TAX_RATES.key?(rate)
|
|
139
|
+
|
|
140
|
+
raise UnsupportedError.new("ezPay takes a tax rate of 0 or 0.05 only, got #{rate.to_f}",
|
|
141
|
+
provider: Client::PROVIDER)
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# ezPay always splits the tax out: +Amt+ excludes it (section 4.3). The
|
|
145
|
+
# split is the core's.
|
|
146
|
+
def issue_amounts(breakdown, mixed)
|
|
147
|
+
fields = { "Amt" => breakdown.sales_amount, "TaxAmt" => breakdown.tax_amount,
|
|
148
|
+
"TotalAmt" => breakdown.total_amount }
|
|
149
|
+
if mixed
|
|
150
|
+
fields["AmtSales"] = breakdown.taxable_amount
|
|
151
|
+
fields["AmtZero"] = breakdown.zero_rated_amount
|
|
152
|
+
fields["AmtFree"] = breakdown.tax_free_amount
|
|
153
|
+
end
|
|
154
|
+
fields
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def buyer_name(buyer, b2b)
|
|
158
|
+
name = buyer&.name.to_s
|
|
159
|
+
if b2b
|
|
160
|
+
return name unless name.empty?
|
|
161
|
+
|
|
162
|
+
return buyer.ubn.to_s
|
|
163
|
+
end
|
|
164
|
+
return CONSUMER_NAME if name.empty?
|
|
165
|
+
|
|
166
|
+
max!(name, 30, "buyer name")
|
|
167
|
+
name
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# +CarrierNum+ is +rawurlencode+d before the query string encodes it again
|
|
171
|
+
# (section 2.2). A member carrier without a code uses the buyer's email.
|
|
172
|
+
def carrier_fields(carrier, buyer)
|
|
173
|
+
return { "CarrierType" => "", "CarrierNum" => "" } unless carrier
|
|
174
|
+
|
|
175
|
+
code = carrier.code.to_s
|
|
176
|
+
code = buyer&.email.to_s if code.empty? && carrier.type == CarrierType::MEMBER
|
|
177
|
+
invalid!("a #{carrier.type} carrier needs a code") if code.empty?
|
|
178
|
+
max!(code, 50, "carrier code")
|
|
179
|
+
|
|
180
|
+
{ "CarrierType" => CARRIER_TYPE.fetch(carrier.type), "CarrierNum" => Crypto.rawurlencode(code) }
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# --- items -------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
# Each item field is one string, items separated by +|+. ezPay fixes the
|
|
186
|
+
# prices by the buyer (section 4.3): without tax for a business (+net+),
|
|
187
|
+
# with tax for a consumer. Both come from the core's lines, so the
|
|
188
|
+
# input's +price_mode+ does not matter.
|
|
189
|
+
def item_fields(items, lines, net:)
|
|
190
|
+
rows = items.zip(lines).map { |item, line| item_row(item, net ? line.net_amount : line.gross_amount) }
|
|
191
|
+
%w[ItemName ItemCount ItemUnit ItemPrice ItemAmt].to_h do |field|
|
|
192
|
+
[field, rows.map { |row| row[field] }.join(ITEM_SEPARATOR)]
|
|
193
|
+
end
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
# ezPay wants +ItemAmt = ItemCount × ItemPrice+ in whole numbers, so the
|
|
197
|
+
# price is the amount over the count, and it has to divide.
|
|
198
|
+
def item_row(item, amount)
|
|
199
|
+
name = item.description.to_s
|
|
200
|
+
unit = item.unit.to_s.empty? ? DEFAULT_UNIT : item.unit.to_s
|
|
201
|
+
[name, unit].each do |text|
|
|
202
|
+
unsupported!("ezPay item text must not contain |: #{text.inspect}") if text.include?("|")
|
|
203
|
+
end
|
|
204
|
+
max!(name, 30, "item description")
|
|
205
|
+
limited!(unit, UNIT_LIMIT, "item unit")
|
|
206
|
+
|
|
207
|
+
count = integer!(item.quantity, "item quantity")
|
|
208
|
+
unsupported!("ezPay needs an item quantity above 0, got #{count}") unless count.positive?
|
|
209
|
+
amount = integer!(amount, "item amount")
|
|
210
|
+
unless (amount % count).zero?
|
|
211
|
+
unsupported!("ezPay needs a whole unit price, but the item amount #{amount} does not divide by #{count}")
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
{ "ItemName" => name, "ItemCount" => count, "ItemUnit" => unit, "ItemPrice" => amount / count,
|
|
215
|
+
"ItemAmt" => amount }
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
# --- allowance ---------------------------------------------------------
|
|
219
|
+
|
|
220
|
+
# --- helpers -----------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
def reason!(reason)
|
|
223
|
+
text = reason.to_s
|
|
224
|
+
invalid!("reason is required") if text.empty?
|
|
225
|
+
limited!(text, REASON_LIMIT, "reason")
|
|
226
|
+
text
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
# ezPay counts "2 Chinese or 6 English characters". A text with any
|
|
230
|
+
# non-ASCII character gets the Chinese limit. The ASCII limits are the
|
|
231
|
+
# MIG's, which the core checks, so only the shorter limit is left here.
|
|
232
|
+
def limited!(text, (ascii, other), field)
|
|
233
|
+
max!(text, text.ascii_only? ? ascii : other, field)
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# The core reads every number as exact, but allows decimals. ezPay does
|
|
237
|
+
# not.
|
|
238
|
+
def integer!(value, field)
|
|
239
|
+
rational = value.to_r
|
|
240
|
+
return rational.to_i if rational.denominator == 1
|
|
241
|
+
|
|
242
|
+
unsupported!("ezPay needs a whole number for #{field}, got #{Number.plain(rational)}")
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
# The core checks the MIG lengths. A shorter limit of ezPay's own is
|
|
246
|
+
# UnsupportedError: another provider may take the value
|
|
247
|
+
# (docs/providers/README.md, "The unified model").
|
|
248
|
+
def max!(value, limit, field)
|
|
249
|
+
return if value.length <= limit
|
|
250
|
+
|
|
251
|
+
unsupported!("ezPay takes a #{field} of at most #{limit} characters")
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# The input breaks a MIG rule, or lacks what the call needs.
|
|
255
|
+
def invalid!(message)
|
|
256
|
+
raise ValidationError.new(message, provider: Client::PROVIDER)
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
# The MIG allows the input, but ezPay does not take it.
|
|
260
|
+
def unsupported!(message)
|
|
261
|
+
raise UnsupportedError.new(message, provider: Client::PROVIDER)
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
def string_keys(hash)
|
|
265
|
+
(hash || {}).to_h.transform_keys(&:to_s)
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
end
|
|
269
|
+
end
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "set"
|
|
4
|
+
|
|
5
|
+
module Einvoice
|
|
6
|
+
module EzPay
|
|
7
|
+
# {Einvoice::Provider} over ezPay 簡單行動支付's e-invoice API (the 標準版
|
|
8
|
+
# manual, EZP_INVI 1.2.2).
|
|
9
|
+
#
|
|
10
|
+
# **Experimental.** It is built from docs/providers/ezpay/invoice.md alone.
|
|
11
|
+
# ezPay has no shared test account, and nobody has run this adapter against
|
|
12
|
+
# ezPay yet. Test it against your own test shop first.
|
|
13
|
+
#
|
|
14
|
+
# ezPay needs facts that a plain invoice number does not carry. The
|
|
15
|
+
# reference from #issue or #query has them:
|
|
16
|
+
#
|
|
17
|
+
# - A query needs the number with +random_code+. ezPay can also find an
|
|
18
|
+
# invoice by order id, but only with its total, so the adapter does not
|
|
19
|
+
# declare QUERY_BY_ORDER_ID.
|
|
20
|
+
# - An allowance needs the invoice's +order_id+, and +buyer_ubn+ to pick
|
|
21
|
+
# prices with or without tax. Without an order id, the adapter queries
|
|
22
|
+
# the invoice by number first.
|
|
23
|
+
#
|
|
24
|
+
# An invoice can only be voided after ezPay uploads it, which happens the
|
|
25
|
+
# next day.
|
|
26
|
+
class Provider < ::Einvoice::Provider
|
|
27
|
+
CAPABILITIES = Set[
|
|
28
|
+
Capability::ISSUE,
|
|
29
|
+
Capability::VOID,
|
|
30
|
+
Capability::ALLOWANCE,
|
|
31
|
+
Capability::VOID_ALLOWANCE,
|
|
32
|
+
Capability::QUERY,
|
|
33
|
+
Capability::B2B,
|
|
34
|
+
Capability::MIXED_TAX
|
|
35
|
+
].freeze
|
|
36
|
+
|
|
37
|
+
VERSION = { issue: "1.5", allowance: "1.3", query: "1.3", other: "1.0" }.freeze
|
|
38
|
+
# InvoiceStatus 1 is "not voided", with or without an allowance, so it
|
|
39
|
+
# has no unified status (docs, section 4.4).
|
|
40
|
+
STATUS = { "2" => InvoiceStatus::VOIDED }.freeze
|
|
41
|
+
# InvoiceStatus 1 is "not voided", with or without an allowance (4.4).
|
|
42
|
+
QUERY_STATUSES = STATUS.values.freeze
|
|
43
|
+
|
|
44
|
+
attr_reader :capabilities, :client
|
|
45
|
+
|
|
46
|
+
def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST, base_url: nil, timeout: 30)
|
|
47
|
+
super()
|
|
48
|
+
@client = Client.new(merchant_id: merchant_id, hash_key: hash_key, hash_iv: hash_iv, mode: mode,
|
|
49
|
+
base_url: base_url, timeout: timeout)
|
|
50
|
+
@capabilities = CAPABILITIES
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def name
|
|
54
|
+
Client::PROVIDER
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def query_statuses
|
|
58
|
+
QUERY_STATUSES
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Call any ezPay path with raw fields, for example
|
|
62
|
+
#
|
|
63
|
+
# provider.raw("/Api/invoice_touch_issue", "1.0", { InvoiceTransNo: "…", … })
|
|
64
|
+
#
|
|
65
|
+
# The encryption and the error mapping are applied as usual. Brace the
|
|
66
|
+
# Hash: an unbraced one is read as keyword arguments.
|
|
67
|
+
def raw(path, version, fields)
|
|
68
|
+
@client.request(path, version, fields)
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# 開立發票 (+invoice_issue+, issued now).
|
|
72
|
+
def issue(input)
|
|
73
|
+
parsed = Input.issue(input, provider: name)
|
|
74
|
+
assert_currency_supported!(parsed.currency)
|
|
75
|
+
result = @client.request("/Api/invoice_issue", VERSION[:issue], Payload.issue(parsed), operation: :issue)
|
|
76
|
+
@client.verify_check_code!(result)
|
|
77
|
+
|
|
78
|
+
IssueInvoiceResult.new(
|
|
79
|
+
invoice_number: result["InvoiceNumber"].to_s,
|
|
80
|
+
invoice_datetime: taipei_time(result["CreateTime"]),
|
|
81
|
+
random_code: result["RandomNum"].to_s,
|
|
82
|
+
order_id: result["MerchantOrderNo"].to_s,
|
|
83
|
+
total_amount: amount(result, "TotalAmt"),
|
|
84
|
+
buyer_ubn: parsed.buyer&.ubn,
|
|
85
|
+
tax_type: parsed.resolved_tax_type,
|
|
86
|
+
tax_rate: parsed.tax_rate,
|
|
87
|
+
status: InvoiceStatus::ISSUED,
|
|
88
|
+
raw: result
|
|
89
|
+
)
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# 作廢發票 (+invoice_invalid+). Only after the next day's upload.
|
|
93
|
+
def void(input)
|
|
94
|
+
parsed = Input.void(input, provider: name)
|
|
95
|
+
result = @client.request("/Api/invoice_invalid", VERSION[:other], Payload.void(parsed), operation: :void)
|
|
96
|
+
VoidInvoiceResult.new(invoice_number: result.fetch("InvoiceNumber", parsed.invoice.number).to_s,
|
|
97
|
+
status: InvoiceStatus::VOIDED, raw: result)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# 開立折讓 (+allowance_issue+, confirmed now). ezPay assigns the
|
|
101
|
+
# allowance number, so +allowance_id+ is not sent. The result has no date.
|
|
102
|
+
# The allowance is confirmed at once, so its date is today in Taipei.
|
|
103
|
+
def allowance(input)
|
|
104
|
+
parsed = Input.allowance(input, provider: name)
|
|
105
|
+
data = Payload.allowance(parsed, original_invoice(parsed.invoice))
|
|
106
|
+
result = @client.request("/Api/allowance_issue", VERSION[:allowance], data, operation: :allowance)
|
|
107
|
+
AllowanceResult.new(
|
|
108
|
+
allowance_number: result["AllowanceNo"].to_s,
|
|
109
|
+
invoice_number: result.fetch("InvoiceNumber", parsed.invoice.number).to_s,
|
|
110
|
+
allowance_date: Taipei.today,
|
|
111
|
+
total_amount: amount(result, "AllowanceAmt"),
|
|
112
|
+
raw: result
|
|
113
|
+
)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# 作廢折讓 (+allowanceInvalid+).
|
|
117
|
+
def void_allowance(input)
|
|
118
|
+
parsed = Input.void_allowance(input, provider: name)
|
|
119
|
+
result = @client.request("/Api/allowanceInvalid", VERSION[:other], Payload.void_allowance(parsed),
|
|
120
|
+
operation: :void_allowance)
|
|
121
|
+
VoidAllowanceResult.new(allowance_number: result.fetch("AllowanceNo", parsed.allowance.allowance_number).to_s,
|
|
122
|
+
raw: result)
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# 查詢發票 (+invoice_search+). See the class comment for the second key.
|
|
126
|
+
#
|
|
127
|
+
# The result has no allowance data, so +status+ is never +ALLOWANCE+.
|
|
128
|
+
def query(input)
|
|
129
|
+
reference = Input.query(input, provider: name).invoice
|
|
130
|
+
assert_supports!(Capability::QUERY_BY_ORDER_ID) if reference.number.nil?
|
|
131
|
+
search(reference)
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
private
|
|
135
|
+
|
|
136
|
+
def search(reference)
|
|
137
|
+
result = @client.request("/Api/invoice_search", VERSION[:query], Payload.query(reference), operation: :query)
|
|
138
|
+
@client.verify_check_code!(result)
|
|
139
|
+
build_query_result(result)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# The invoice's order id, and whether its buyer is a business (docs,
|
|
143
|
+
# section 4.1). From the reference when it has the order id, else from a
|
|
144
|
+
# query by number. A failed query is the provider's error, not the
|
|
145
|
+
# invoice's: a NotFoundError would read as "the invoice of this call does
|
|
146
|
+
# not exist".
|
|
147
|
+
def original_invoice(reference)
|
|
148
|
+
return { order_id: reference.order_id, business: !reference.buyer_ubn.nil? } if reference.order_id
|
|
149
|
+
unless Payload.queryable?(reference)
|
|
150
|
+
raise ValidationError.new("an ezPay allowance needs invoice.order_id, or invoice.random_code to look it up",
|
|
151
|
+
provider: name)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
found = begin
|
|
155
|
+
search(reference)
|
|
156
|
+
rescue Error => e
|
|
157
|
+
raise ProviderError.new("allowance needs the invoice's order id; looking it up failed: #{e.message}",
|
|
158
|
+
provider: name, reason: Reason::LOOKUP_FAILED, cause: e)
|
|
159
|
+
end
|
|
160
|
+
if found.order_id.nil?
|
|
161
|
+
raise ProviderError.new("allowance needs the invoice's order id; the invoice found has none",
|
|
162
|
+
provider: name, reason: Reason::LOOKUP_FAILED)
|
|
163
|
+
end
|
|
164
|
+
{ order_id: found.order_id, business: !found.buyer.ubn.nil? }
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def build_query_result(result)
|
|
168
|
+
tax_type = TAX_TYPE[result["TaxType"].to_s]
|
|
169
|
+
items = TaxType.fill_items(item_detail(result["ItemDetail"]).map { |row| build_item(row) }, tax_type)
|
|
170
|
+
QueryInvoiceResult.new(
|
|
171
|
+
invoice_number: result["InvoiceNumber"].to_s,
|
|
172
|
+
invoice_datetime: taipei_time(result["CreateTime"]),
|
|
173
|
+
random_code: result["RandomNum"].to_s,
|
|
174
|
+
order_id: presence(result["MerchantOrderNo"]),
|
|
175
|
+
status: STATUS[result["InvoiceStatus"].to_s],
|
|
176
|
+
amount: query_amount(result),
|
|
177
|
+
buyer: Buyer.new(name: presence(result["BuyerName"]), ubn: presence(result["BuyerUBN"]),
|
|
178
|
+
email: presence(result["BuyerEmail"]), address: presence(result["BuyerAddress"]),
|
|
179
|
+
phone: presence(result["BuyerPhone"])),
|
|
180
|
+
items: items,
|
|
181
|
+
tax_type: tax_type,
|
|
182
|
+
tax_rate: query_rate(result["TaxRate"]),
|
|
183
|
+
raw: result
|
|
184
|
+
)
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
# ezPay TaxType → unified 課稅別. 9 is mixed.
|
|
188
|
+
TAX_TYPE = Payload::TAX_TYPE.invert.merge(Payload::MIXED_TAX_CODE => TaxType::MIXED).freeze
|
|
189
|
+
|
|
190
|
+
# The query returns the rate as a fraction, for example "0.05000". A rate
|
|
191
|
+
# that is not a MIG rate reads as nil.
|
|
192
|
+
def query_rate(reported)
|
|
193
|
+
Input.mig_rate!(reported, "TaxRate", name)
|
|
194
|
+
rescue ValidationError
|
|
195
|
+
nil
|
|
196
|
+
end
|
|
197
|
+
|
|
198
|
+
# +ItemDetail+ is a JSON string inside +Result+.
|
|
199
|
+
def item_detail(value)
|
|
200
|
+
rows = value.is_a?(String) && !value.strip.empty? ? JSON.parse(value) : value
|
|
201
|
+
Array(rows).select { |row| row.is_a?(Hash) }
|
|
202
|
+
rescue JSON::ParserError => e
|
|
203
|
+
raise ProviderError.new("ezPay returned an ItemDetail that is not JSON", provider: name, raw: value,
|
|
204
|
+
cause: e)
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
def build_item(row)
|
|
208
|
+
InvoiceItem.new(
|
|
209
|
+
description: row["ItemName"].to_s,
|
|
210
|
+
quantity: item_number(row, "ItemCount"),
|
|
211
|
+
unit_price: item_number(row, "ItemPrice"),
|
|
212
|
+
amount: item_number(row, "ItemAmount"),
|
|
213
|
+
unit: presence(row["ItemWord"]),
|
|
214
|
+
tax_type: Payload::TAX_TYPE.invert[row["ItemTaxType"].to_s],
|
|
215
|
+
remark: nil
|
|
216
|
+
)
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
# A total as a whole number. Nobody has run the adapter against ezPay,
|
|
220
|
+
# so no live response shows if a total can be missing. A missing one
|
|
221
|
+
# reads as 0, as before. A value that is not a whole number is an error.
|
|
222
|
+
def amount(result, field)
|
|
223
|
+
Number.response_integer!(result[field], field: field, provider: name, raw: result, if_missing: 0)
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
# ezPay reads the three totals apart, so they can disagree. A result
|
|
227
|
+
# where sales and tax do not add up to the total is not a MIG invoice.
|
|
228
|
+
def query_amount(result)
|
|
229
|
+
sales, tax, total = %w[Amt TaxAmt TotalAmt].map { |field| amount(result, field) }
|
|
230
|
+
return AmountSummary.new(sales_amount: sales, tax_amount: tax, total_amount: total) if sales + tax == total
|
|
231
|
+
|
|
232
|
+
raise ProviderError.new("the ezpay response has Amt #{sales} and TaxAmt #{tax}, " \
|
|
233
|
+
"which do not add up to TotalAmt #{total}", provider: name, raw: result)
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# A missing item number is nil, not 0.
|
|
237
|
+
def item_number(row, field)
|
|
238
|
+
Number.response_plain(row[field], field: "ItemDetail #{field}", provider: name, raw: row)
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
def presence(value)
|
|
242
|
+
string = value.to_s
|
|
243
|
+
string.empty? ? nil : string
|
|
244
|
+
end
|
|
245
|
+
|
|
246
|
+
# "2015-11-03 17:58:36" (UTC+8) → Time, or nil.
|
|
247
|
+
def taipei_time(value)
|
|
248
|
+
match = /\A(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\z/.match(value.to_s)
|
|
249
|
+
match && Time.new(*match.captures.map(&:to_i), "+08:00")
|
|
250
|
+
end
|
|
251
|
+
end
|
|
252
|
+
end
|
|
253
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "einvoice"
|
|
4
|
+
require "einvoice/ezpay/crypto"
|
|
5
|
+
require "einvoice/ezpay/errors"
|
|
6
|
+
require "einvoice/ezpay/client"
|
|
7
|
+
require "einvoice/ezpay/payload"
|
|
8
|
+
require "einvoice/ezpay/provider"
|
|
9
|
+
|
|
10
|
+
module Einvoice
|
|
11
|
+
# Adapter for ezPay 簡單行動支付's e-invoice API. Experimental: see
|
|
12
|
+
# {Provider}.
|
|
13
|
+
#
|
|
14
|
+
# The wire format is a form POST whose +PostData_+ is a PHP query string,
|
|
15
|
+
# encrypted with AES-256-CBC and hex encoded. None of that reaches
|
|
16
|
+
# application code: {Provider} exposes only the unified model.
|
|
17
|
+
module EzPay
|
|
18
|
+
end
|
|
19
|
+
end
|