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.
- checksums.yaml +4 -4
- data/.coderabbit.yaml +12 -0
- data/.github/workflows/build.yml +7 -4
- data/CHANGELOG.md +55 -35
- data/Gemfile +3 -2
- data/README.md +230 -265
- data/README.zh-TW.md +322 -0
- data/Rakefile +2 -13
- data/bin/console +3 -6
- data/einvoice.gemspec +24 -21
- data/lib/einvoice/amego/client.rb +116 -0
- data/lib/einvoice/amego/errors.rb +84 -0
- data/lib/einvoice/amego/payload.rb +276 -0
- data/lib/einvoice/amego/provider.rb +267 -0
- data/lib/einvoice/amego.rb +27 -0
- data/lib/einvoice/capability.rb +79 -0
- data/lib/einvoice/ecpay/client.rb +183 -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 +362 -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 +235 -0
- data/lib/einvoice/ezpay.rb +19 -0
- data/lib/einvoice/input.rb +494 -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 +51 -0
- data/lib/einvoice/provider.rb +57 -14
- data/lib/einvoice/redaction.rb +54 -0
- data/lib/einvoice/taipei.rb +89 -0
- data/lib/einvoice/tax_split.rb +124 -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 +366 -0
- data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
- data/lib/einvoice/tradevan.rb +25 -0
- data/lib/einvoice/types.rb +323 -0
- data/lib/einvoice/version.rb +3 -1
- data/lib/einvoice.rb +21 -10
- metadata +60 -176
- data/.github/workflows/cron.yml +0 -31
- 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 -2022
- 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 -140
- data/lib/einvoice/tradevan/result.rb +0 -25
- data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
- data/lib/einvoice/utils.rb +0 -13
- data/lib/faraday/response/decode_tradevan.rb +0 -38
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "date"
|
|
4
|
+
|
|
5
|
+
module Einvoice
|
|
6
|
+
module Amego
|
|
7
|
+
# Maps the unified value model onto Amego's JSON payloads, and checks the
|
|
8
|
+
# rules from docs/providers/amego/api.md locally, so a bad request fails
|
|
9
|
+
# before the network. The core has already checked the input and computed
|
|
10
|
+
# the tax, so this module only translates.
|
|
11
|
+
module Payload
|
|
12
|
+
# 課稅別 → Amego TaxType. 9 (混合) is derived from the items.
|
|
13
|
+
TAX_TYPE = {
|
|
14
|
+
TaxType::TAXABLE => "1",
|
|
15
|
+
TaxType::ZERO_RATED => "2",
|
|
16
|
+
TaxType::TAX_FREE => "3"
|
|
17
|
+
}.freeze
|
|
18
|
+
MIXED_TAX_CODE = "9"
|
|
19
|
+
|
|
20
|
+
CARRIER_TYPE = {
|
|
21
|
+
CarrierType::MOBILE_BARCODE => "3J0002",
|
|
22
|
+
CarrierType::CITIZEN_CERTIFICATE => "CQ0001",
|
|
23
|
+
CarrierType::MEMBER => "amego" # Amego's own member carrier
|
|
24
|
+
}.freeze
|
|
25
|
+
|
|
26
|
+
CONSUMER_ID = "0000000000"
|
|
27
|
+
CONSUMER_NAME = "消費者"
|
|
28
|
+
ALLOWANCE_TYPE = "2" # 賣方開立. Amego rejects 1 since 2025-01-01
|
|
29
|
+
# The only rates TaxRate takes (docs, section 4.2).
|
|
30
|
+
TAX_RATES = [0r, Rational(5, 100)].freeze
|
|
31
|
+
MOBILE_MEMBER = /\A09\d{8}\z/
|
|
32
|
+
|
|
33
|
+
MAX_ORDER_ID = 40
|
|
34
|
+
MAX_DESCRIPTION = 256
|
|
35
|
+
MAX_ALLOWANCE_NUMBER = 16
|
|
36
|
+
|
|
37
|
+
# provider_options key => f0401 field, for fields with no unified home.
|
|
38
|
+
ISSUE_OPTIONS = {
|
|
39
|
+
"track_api_code" => "TrackApiCode",
|
|
40
|
+
"brand_name" => "BrandName",
|
|
41
|
+
"detail_amount_round" => "DetailAmountRound",
|
|
42
|
+
"tax_adjustment" => "TaxAdjustment"
|
|
43
|
+
}.freeze
|
|
44
|
+
|
|
45
|
+
module_function
|
|
46
|
+
|
|
47
|
+
# +f0401+ data from a parsed {IssueInvoiceInput}.
|
|
48
|
+
def issue(parsed)
|
|
49
|
+
b2b = parsed.resolved_category == InvoiceCategory::B2B
|
|
50
|
+
exclusive = parsed.price_mode == PriceMode::TAX_EXCLUSIVE
|
|
51
|
+
options = string_keys(parsed.provider_options)
|
|
52
|
+
types = parsed.items.map { |item| item.tax_type || parsed.tax_type }
|
|
53
|
+
check_issue!(parsed, types, b2b, exclusive)
|
|
54
|
+
breakdown = parsed.tax_breakdown(provider: Client::PROVIDER)
|
|
55
|
+
|
|
56
|
+
data = {
|
|
57
|
+
"OrderId" => parsed.order_id.to_s,
|
|
58
|
+
"BuyerIdentifier" => b2b ? parsed.buyer.ubn.to_s : CONSUMER_ID,
|
|
59
|
+
"BuyerName" => buyer_name(parsed.buyer, b2b),
|
|
60
|
+
"BuyerAddress" => parsed.buyer&.address.to_s,
|
|
61
|
+
"BuyerTelephoneNumber" => parsed.buyer&.phone.to_s,
|
|
62
|
+
"BuyerEmailAddress" => parsed.buyer&.email.to_s,
|
|
63
|
+
"MainRemark" => parsed.remark.to_s,
|
|
64
|
+
**carrier_fields(parsed.carrier, parsed.buyer),
|
|
65
|
+
"NPOBAN" => parsed.donation&.npoban.to_s,
|
|
66
|
+
"ProductItem" => parsed.items.zip(types).map { |item, type| issue_item(item, type) },
|
|
67
|
+
**issue_totals(breakdown, b2b),
|
|
68
|
+
"TaxType" => types.uniq.size > 1 ? MIXED_TAX_CODE : TAX_TYPE.fetch(types.first),
|
|
69
|
+
"TaxRate" => number(parsed.tax_rate),
|
|
70
|
+
"DetailVat" => exclusive ? "0" : "1"
|
|
71
|
+
}
|
|
72
|
+
if parsed.zero_rated?
|
|
73
|
+
data["CustomsClearanceMark"] = parsed.customs_clearance_mark
|
|
74
|
+
data["ZeroTaxRateReason"] = parsed.zero_tax_rate_reason
|
|
75
|
+
end
|
|
76
|
+
ISSUE_OPTIONS.each { |key, field| data[field] = options[key].to_s if options.key?(key) }
|
|
77
|
+
data
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# +f0501+ data: one invoice per call. The core checks the reason's length.
|
|
81
|
+
def void(parsed)
|
|
82
|
+
[{ "CancelInvoiceNumber" => parsed.invoice.number.to_s, "CancelReason" => parsed.reason.to_s }]
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# +g0401+ data. +original+ carries the facts about the original invoice
|
|
86
|
+
# that the reference may not have: +buyer_identifier+, +buyer_name+ and
|
|
87
|
+
# +invoice_datetime+.
|
|
88
|
+
def allowance(parsed, original, allowance_date)
|
|
89
|
+
number = parsed.allowance_id.to_s
|
|
90
|
+
# Amego sends allowance_id as the MIG AllowanceNumber. Other providers
|
|
91
|
+
# number an allowance themselves, so this limit is Amego's.
|
|
92
|
+
max!(number, MAX_ALLOWANCE_NUMBER, "allowance_id")
|
|
93
|
+
breakdown = parsed.tax_breakdown(provider: Client::PROVIDER)
|
|
94
|
+
refuse_special!(breakdown.lines.map(&:tax_type))
|
|
95
|
+
check_rate!(parsed.tax_rate)
|
|
96
|
+
invoice_date = ymd(original[:invoice_datetime])
|
|
97
|
+
|
|
98
|
+
[{
|
|
99
|
+
"AllowanceNumber" => number,
|
|
100
|
+
"AllowanceDate" => allowance_date.strftime("%Y%m%d"),
|
|
101
|
+
"AllowanceType" => ALLOWANCE_TYPE,
|
|
102
|
+
"BuyerIdentifier" => original[:buyer_identifier].to_s,
|
|
103
|
+
"BuyerName" => original[:buyer_name].to_s,
|
|
104
|
+
"ProductItem" => parsed.items.zip(breakdown.lines).map do |item, line|
|
|
105
|
+
allowance_item(item, line).merge("OriginalInvoiceNumber" => parsed.invoice.number.to_s,
|
|
106
|
+
"OriginalInvoiceDate" => invoice_date)
|
|
107
|
+
end,
|
|
108
|
+
"TaxAmount" => breakdown.tax_amount,
|
|
109
|
+
"TotalAmount" => breakdown.sales_amount
|
|
110
|
+
}]
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# +g0501+ data.
|
|
114
|
+
def void_allowance(parsed)
|
|
115
|
+
[{ "CancelAllowanceNumber" => parsed.allowance.allowance_number.to_s }]
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# +invoice_query+ data. The order id wins when the reference has both.
|
|
119
|
+
def query(reference)
|
|
120
|
+
if reference.order_id.nil?
|
|
121
|
+
{ "type" => "invoice", "invoice_number" => reference.number.to_s }
|
|
122
|
+
else
|
|
123
|
+
{ "type" => "order", "order_id" => reference.order_id.to_s }
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
# --- issue -------------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
def check_issue!(parsed, types, b2b, exclusive)
|
|
130
|
+
max!(parsed.order_id.to_s, MAX_ORDER_ID, "order_id")
|
|
131
|
+
unsupported!("Amego takes tax-exclusive prices only for a B2B invoice") if exclusive && !b2b
|
|
132
|
+
refuse_special!(types)
|
|
133
|
+
check_rate!(parsed.tax_rate)
|
|
134
|
+
# The core asks for the clearance mark. The MIG asks for the reason too,
|
|
135
|
+
# and so does Amego.
|
|
136
|
+
return unless parsed.zero_rated? && parsed.zero_tax_rate_reason.nil?
|
|
137
|
+
|
|
138
|
+
invalid!("a zero-rated invoice needs zero_tax_rate_reason (71 to 79)")
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def refuse_special!(types)
|
|
142
|
+
return unless types.include?(TaxType::SPECIAL)
|
|
143
|
+
|
|
144
|
+
raise UnsupportedError.new("Amego adapter does not support special tax (特種稅額)",
|
|
145
|
+
provider: Client::PROVIDER)
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
# The core has checked that +rate+ is a MIG rate. Amego takes two of them.
|
|
149
|
+
def check_rate!(rate)
|
|
150
|
+
return if TAX_RATES.include?(rate)
|
|
151
|
+
|
|
152
|
+
raise UnsupportedError.new("Amego takes a tax rate of 0 or 0.05 only, got #{number(rate)}",
|
|
153
|
+
provider: Client::PROVIDER)
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# The MIG totals from the core's breakdown (docs, section 4.3). A B2C
|
|
157
|
+
# invoice keeps the tax inside SalesAmount, as F0401 does.
|
|
158
|
+
def issue_totals(breakdown, b2b)
|
|
159
|
+
sales = breakdown.taxable_amount
|
|
160
|
+
tax = breakdown.tax_amount
|
|
161
|
+
sales, tax = sales + tax, 0 unless b2b
|
|
162
|
+
{ "SalesAmount" => sales, "FreeTaxSalesAmount" => breakdown.tax_free_amount,
|
|
163
|
+
"ZeroTaxSalesAmount" => breakdown.zero_rated_amount, "TaxAmount" => tax,
|
|
164
|
+
"TotalAmount" => breakdown.total_amount }
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def buyer_name(buyer, b2b)
|
|
168
|
+
name = buyer&.name.to_s
|
|
169
|
+
return name unless name.empty?
|
|
170
|
+
|
|
171
|
+
b2b ? buyer.ubn.to_s : CONSUMER_NAME
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# Visible and hidden codes are the same. A member carrier without a code
|
|
175
|
+
# uses the buyer's email, else +a+ and the buyer's mobile number.
|
|
176
|
+
def carrier_fields(carrier, buyer)
|
|
177
|
+
return { "CarrierType" => "", "CarrierId1" => "", "CarrierId2" => "" } unless carrier
|
|
178
|
+
|
|
179
|
+
code = carrier.code.to_s
|
|
180
|
+
code = member_code(buyer) if code.empty? && carrier.type == CarrierType::MEMBER
|
|
181
|
+
invalid!("a #{carrier.type} carrier needs a code") if code.empty?
|
|
182
|
+
|
|
183
|
+
{ "CarrierType" => CARRIER_TYPE.fetch(carrier.type), "CarrierId1" => code, "CarrierId2" => code }
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def member_code(buyer)
|
|
187
|
+
email = buyer&.email.to_s
|
|
188
|
+
return email unless email.empty?
|
|
189
|
+
|
|
190
|
+
phone = buyer&.phone.to_s.delete("- ")
|
|
191
|
+
phone.match?(MOBILE_MEMBER) ? "a#{phone}" : ""
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
def issue_item(item, type)
|
|
195
|
+
description = item.description.to_s
|
|
196
|
+
max!(description, MAX_DESCRIPTION, "item description")
|
|
197
|
+
{
|
|
198
|
+
"Description" => description,
|
|
199
|
+
"Quantity" => number(item.quantity),
|
|
200
|
+
"Unit" => item.unit.to_s,
|
|
201
|
+
"UnitPrice" => number(item.unit_price),
|
|
202
|
+
"Amount" => number(item.amount),
|
|
203
|
+
"Remark" => item.remark.to_s,
|
|
204
|
+
"TaxType" => TAX_TYPE.fetch(type)
|
|
205
|
+
}
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
# --- allowance ---------------------------------------------------------
|
|
209
|
+
|
|
210
|
+
# Amego wants allowance amounts without tax, and an integer +Tax+ on each
|
|
211
|
+
# item (docs, section 4.3). Both come from the core's line. The unit price
|
|
212
|
+
# is the amount over the quantity, rounded to 7 decimal places, so
|
|
213
|
+
# +UnitPrice × Quantity+ can miss +Amount+ by that rounding: 94 over 3 is
|
|
214
|
+
# 31.3333333. The core's +net_unit_price+ is not used, because it comes
|
|
215
|
+
# from the item's unit price and can miss by the rounding of the tax.
|
|
216
|
+
def allowance_item(item, line)
|
|
217
|
+
description = item.description.to_s
|
|
218
|
+
max!(description, MAX_DESCRIPTION, "item description")
|
|
219
|
+
{
|
|
220
|
+
"OriginalDescription" => description,
|
|
221
|
+
"Quantity" => number(item.quantity),
|
|
222
|
+
"UnitPrice" => number(unit_price(line.net_amount, item.quantity)),
|
|
223
|
+
"Amount" => number(line.net_amount),
|
|
224
|
+
"Tax" => line.tax,
|
|
225
|
+
"TaxType" => TAX_TYPE.fetch(line.tax_type)
|
|
226
|
+
}
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def unit_price(amount, quantity)
|
|
230
|
+
quantity = quantity.to_r
|
|
231
|
+
quantity.zero? ? amount.to_r : amount.to_r / quantity
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
# --- helpers -----------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
# Amego takes up to 7 decimals. Whole numbers go out without a point. The
|
|
237
|
+
# core has already read every number as exact.
|
|
238
|
+
# Rounds to 7 decimal places first, so a value that rounds to a whole
|
|
239
|
+
# number is written without a point: "100", not "100.".
|
|
240
|
+
def number(value)
|
|
241
|
+
rational = value.to_r.round(7)
|
|
242
|
+
return rational.to_i.to_s if rational.denominator == 1
|
|
243
|
+
|
|
244
|
+
format("%.7f", rational).sub(/0+\z/, "")
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
# A Time → "Ymd" in Taipei time.
|
|
248
|
+
def ymd(time)
|
|
249
|
+
Taipei.date(time, provider: Client::PROVIDER).strftime("%Y%m%d")
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
# The core checks the MIG lengths. A shorter limit of Amego's own is
|
|
253
|
+
# UnsupportedError: another provider may take the value
|
|
254
|
+
# (docs/providers/README.md, "The unified model").
|
|
255
|
+
def max!(value, limit, field)
|
|
256
|
+
return if value.length <= limit
|
|
257
|
+
|
|
258
|
+
unsupported!("Amego takes a #{field} of at most #{limit} characters")
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
# The input breaks a MIG rule, or lacks what the call needs.
|
|
262
|
+
def invalid!(message)
|
|
263
|
+
raise ValidationError.new(message, provider: Client::PROVIDER)
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# The MIG allows the input, but Amego does not take it.
|
|
267
|
+
def unsupported!(message)
|
|
268
|
+
raise UnsupportedError.new(message, provider: Client::PROVIDER)
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
def string_keys(hash)
|
|
272
|
+
(hash || {}).to_h.transform_keys(&:to_s)
|
|
273
|
+
end
|
|
274
|
+
end
|
|
275
|
+
end
|
|
276
|
+
end
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "set"
|
|
4
|
+
|
|
5
|
+
module Einvoice
|
|
6
|
+
module Amego
|
|
7
|
+
# {Einvoice::Provider} over Amego 光貿's JSON API, with 自動配號: Amego picks
|
|
8
|
+
# the invoice number.
|
|
9
|
+
#
|
|
10
|
+
# docs/providers/amego/api.md describes the API and the choices below.
|
|
11
|
+
#
|
|
12
|
+
# Two behaviours to know:
|
|
13
|
+
#
|
|
14
|
+
# - A void is queued. Amego accepts it at once, but a query right after it
|
|
15
|
+
# can still report the invoice as issued.
|
|
16
|
+
# - An allowance needs the original invoice's buyer and date. The reference
|
|
17
|
+
# has the date and the 統一編號, but not the buyer's name, so the adapter
|
|
18
|
+
# queries the invoice for it, unless +provider_options+ gives +buyer_name+
|
|
19
|
+
# and the reference has +invoice_datetime+. The query only works within
|
|
20
|
+
# 180 days.
|
|
21
|
+
class Provider < ::Einvoice::Provider
|
|
22
|
+
CAPABILITIES = Set[
|
|
23
|
+
Capability::ISSUE,
|
|
24
|
+
Capability::VOID,
|
|
25
|
+
Capability::ALLOWANCE,
|
|
26
|
+
Capability::VOID_ALLOWANCE,
|
|
27
|
+
Capability::QUERY,
|
|
28
|
+
Capability::QUERY_BY_ORDER_ID,
|
|
29
|
+
Capability::B2B,
|
|
30
|
+
Capability::MIXED_TAX,
|
|
31
|
+
Capability::CARRIER_VALIDATION
|
|
32
|
+
].freeze
|
|
33
|
+
|
|
34
|
+
# The barcode code for a mobile barcode that is not registered.
|
|
35
|
+
UNREGISTERED_BARCODE = "9000113"
|
|
36
|
+
|
|
37
|
+
VOID_TYPES = %w[C0501 A0501 A0201 A0202].freeze
|
|
38
|
+
ISSUE_TYPES = %w[C0401 A0401 A0101 A0102].freeze
|
|
39
|
+
LIVE_ALLOWANCE_TYPES = %w[D0401 G0401 B0401 B0101 B0102].freeze
|
|
40
|
+
|
|
41
|
+
attr_reader :capabilities, :client
|
|
42
|
+
|
|
43
|
+
def initialize(ban:, app_key:, base_url: Client::BASE_URL, timeout: 30, clock: -> { Time.now })
|
|
44
|
+
super()
|
|
45
|
+
@client = Client.new(ban: ban, app_key: app_key, base_url: base_url, timeout: timeout, clock: clock)
|
|
46
|
+
@clock = clock
|
|
47
|
+
@capabilities = CAPABILITIES
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def name
|
|
51
|
+
Client::PROVIDER
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Call any Amego path with a raw payload, for example
|
|
55
|
+
#
|
|
56
|
+
# provider.raw("/json/barcode", { barCode: "/ABC1234" })
|
|
57
|
+
#
|
|
58
|
+
# The signing and the error mapping are applied as usual. Brace the Hash:
|
|
59
|
+
# an unbraced one is read as keyword arguments.
|
|
60
|
+
def raw(path, payload)
|
|
61
|
+
@client.request(path, payload)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# 開立發票 (+f0401+).
|
|
65
|
+
def issue(input)
|
|
66
|
+
parsed = Input.issue(input, provider: name)
|
|
67
|
+
assert_currency_supported!(parsed.currency)
|
|
68
|
+
result = @client.request("/json/f0401", Payload.issue(parsed))
|
|
69
|
+
|
|
70
|
+
IssueInvoiceResult.new(
|
|
71
|
+
invoice_number: result["invoice_number"].to_s,
|
|
72
|
+
invoice_datetime: unix_time(result["invoice_time"]),
|
|
73
|
+
random_code: result["random_number"].to_s,
|
|
74
|
+
order_id: parsed.order_id,
|
|
75
|
+
total_amount: parsed.amount.total_amount,
|
|
76
|
+
buyer_ubn: parsed.buyer&.ubn,
|
|
77
|
+
tax_type: TaxType.of(parsed.items, parsed.tax_type),
|
|
78
|
+
tax_rate: parsed.tax_rate,
|
|
79
|
+
status: InvoiceStatus::ISSUED,
|
|
80
|
+
raw: result
|
|
81
|
+
)
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# 作廢發票 (+f0501+). The void is queued: see the class comment.
|
|
85
|
+
def void(input)
|
|
86
|
+
parsed = Input.void(input, provider: name)
|
|
87
|
+
result = @client.request("/json/f0501", Payload.void(parsed))
|
|
88
|
+
VoidInvoiceResult.new(invoice_number: parsed.invoice.number, status: InvoiceStatus::VOIDED, raw: result)
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
# 開立折讓 (+g0401+). The seller assigns the allowance number, so the
|
|
92
|
+
# result's +allowance_number+ is the input's +allowance_id+. The allowance
|
|
93
|
+
# date is today in Taipei.
|
|
94
|
+
def allowance(input)
|
|
95
|
+
parsed = Input.allowance(input, provider: name)
|
|
96
|
+
allowance_date = Taipei.date(@clock.call)
|
|
97
|
+
data = Payload.allowance(parsed, original_invoice(parsed), allowance_date)
|
|
98
|
+
result = @client.request("/json/g0401", data)
|
|
99
|
+
|
|
100
|
+
AllowanceResult.new(
|
|
101
|
+
allowance_number: parsed.allowance_id.to_s,
|
|
102
|
+
invoice_number: parsed.invoice.number,
|
|
103
|
+
allowance_date: allowance_date,
|
|
104
|
+
total_amount: parsed.amount.total_amount,
|
|
105
|
+
raw: result
|
|
106
|
+
)
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
# 作廢折讓 (+g0501+). Amego takes no reason here.
|
|
110
|
+
def void_allowance(input)
|
|
111
|
+
parsed = Input.void_allowance(input, provider: name)
|
|
112
|
+
result = @client.request("/json/g0501", Payload.void_allowance(parsed))
|
|
113
|
+
VoidAllowanceResult.new(allowance_number: parsed.allowance.allowance_number, raw: result)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# 查詢發票 (+invoice_query+), by order id when the reference has one, else
|
|
117
|
+
# by invoice number. Within 180 days of the invoice.
|
|
118
|
+
def query(input)
|
|
119
|
+
reference = Input.query(input, provider: name).invoice
|
|
120
|
+
assert_supports!(Capability::QUERY_BY_ORDER_ID) if reference.order_id
|
|
121
|
+
build_query_result(fetch_invoice(Payload.query(reference)))
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# Whether a carrier is registered (+barcode+). Amego can check a 手機條碼
|
|
125
|
+
# only. For a donation code, use {Einvoice::MOF::DonationCodes}.
|
|
126
|
+
def validate_carrier(carrier)
|
|
127
|
+
parsed = Input.carrier(carrier, provider: name)
|
|
128
|
+
unless parsed.type == CarrierType::MOBILE_BARCODE
|
|
129
|
+
raise UnsupportedError.new("Amego can check a mobile barcode only, not #{parsed.type}", provider: name)
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
begin
|
|
133
|
+
@client.request("/json/barcode", { "barCode" => parsed.code })
|
|
134
|
+
rescue Error => e
|
|
135
|
+
return false if e.raw_code == UNREGISTERED_BARCODE
|
|
136
|
+
|
|
137
|
+
raise
|
|
138
|
+
end
|
|
139
|
+
true
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
private
|
|
143
|
+
|
|
144
|
+
def fetch_invoice(payload)
|
|
145
|
+
data = @client.request("/json/invoice_query", payload)["data"]
|
|
146
|
+
return data if data.is_a?(Hash)
|
|
147
|
+
|
|
148
|
+
raise ProviderError.new("Amego returned no invoice data", provider: name, raw: data)
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# The original invoice's buyer and date (docs, section 4.1). The reference
|
|
152
|
+
# has the date and the 統一編號. The buyer's name comes from
|
|
153
|
+
# +provider_options+, else from a query. A failed query is the provider's
|
|
154
|
+
# error, not the invoice's: a NotFoundError would read as "the invoice of
|
|
155
|
+
# this call does not exist".
|
|
156
|
+
def original_invoice(parsed)
|
|
157
|
+
reference = parsed.invoice
|
|
158
|
+
buyer_name = Payload.string_keys(parsed.provider_options)["buyer_name"]
|
|
159
|
+
if buyer_name && reference.invoice_datetime
|
|
160
|
+
return { buyer_identifier: reference.buyer_ubn || Payload::CONSUMER_ID, buyer_name: buyer_name,
|
|
161
|
+
invoice_datetime: reference.invoice_datetime }
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
found = lookup(reference.number)
|
|
165
|
+
if found.invoice_datetime.nil?
|
|
166
|
+
raise ProviderError.new("allowance needs the invoice date; the invoice found by number has none",
|
|
167
|
+
provider: name, reason: Reason::LOOKUP_FAILED)
|
|
168
|
+
end
|
|
169
|
+
{ buyer_identifier: reference.buyer_ubn || found.buyer.ubn || Payload::CONSUMER_ID,
|
|
170
|
+
buyer_name: buyer_name || found.buyer.name.to_s,
|
|
171
|
+
invoice_datetime: reference.invoice_datetime || found.invoice_datetime }
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
def lookup(number)
|
|
175
|
+
build_query_result(fetch_invoice(Payload.query(InvoiceReference.new(number: number))))
|
|
176
|
+
rescue Error => e
|
|
177
|
+
raise ProviderError.new("allowance needs the invoice's buyer and date; looking them up failed: #{e.message}",
|
|
178
|
+
provider: name, reason: Reason::LOOKUP_FAILED, cause: e)
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def build_query_result(data)
|
|
182
|
+
tax = data["tax_amount"].to_i
|
|
183
|
+
total = data["total_amount"].to_i
|
|
184
|
+
items = Array(data["product_item"]).map { |row| build_item(row) }
|
|
185
|
+
QueryInvoiceResult.new(
|
|
186
|
+
invoice_number: data["invoice_number"].to_s,
|
|
187
|
+
invoice_datetime: taipei_time(data["invoice_date"], data["invoice_time"]),
|
|
188
|
+
random_code: data["random_number"].to_s,
|
|
189
|
+
order_id: presence(data["order_id"]),
|
|
190
|
+
status: status_of(data),
|
|
191
|
+
amount: AmountSummary.new(sales_amount: total - tax, tax_amount: tax, total_amount: total),
|
|
192
|
+
buyer: build_buyer(data),
|
|
193
|
+
items: items,
|
|
194
|
+
tax_type: items.empty? || items.any? { |item| item.tax_type.nil? } ? nil : TaxType.of(items, nil),
|
|
195
|
+
tax_rate: query_rate(data["tax_rate"]),
|
|
196
|
+
raw: data
|
|
197
|
+
)
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
# A rate that is not a MIG rate reads as nil, so an allowance has to give
|
|
201
|
+
# one.
|
|
202
|
+
def query_rate(reported)
|
|
203
|
+
Input.mig_rate!(reported, "tax_rate", name)
|
|
204
|
+
rescue ValidationError
|
|
205
|
+
nil
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
# docs, section 4.4. A cancelled (+C0701+) or rejected (+A0301+, +A0302+)
|
|
209
|
+
# invoice has no unified status, so it is nil. The raw type stays in
|
|
210
|
+
# +raw["invoice_type"]+.
|
|
211
|
+
def status_of(data)
|
|
212
|
+
type = data["invoice_type"].to_s
|
|
213
|
+
return InvoiceStatus::VOIDED if VOID_TYPES.include?(type)
|
|
214
|
+
return nil unless ISSUE_TYPES.include?(type)
|
|
215
|
+
|
|
216
|
+
live = Array(data["allowance"]).any? { |row| LIVE_ALLOWANCE_TYPES.include?(row["invoice_type"].to_s) }
|
|
217
|
+
live ? InvoiceStatus::ALLOWANCE : InvoiceStatus::ISSUED
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def build_buyer(data)
|
|
221
|
+
id = data["buyer_identifier"].to_s
|
|
222
|
+
Buyer.new(name: presence(data["buyer_name"]),
|
|
223
|
+
ubn: id.empty? || id == Payload::CONSUMER_ID ? nil : id,
|
|
224
|
+
email: presence(data["buyer_email_address"]),
|
|
225
|
+
address: presence(data["buyer_address"]),
|
|
226
|
+
phone: presence(data["buyer_telephone_number"]))
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
def build_item(row)
|
|
230
|
+
InvoiceItem.new(
|
|
231
|
+
description: row["description"].to_s,
|
|
232
|
+
quantity: numeric(row["quantity"]),
|
|
233
|
+
unit_price: numeric(row["unit_price"]),
|
|
234
|
+
amount: numeric(row["amount"]),
|
|
235
|
+
unit: presence(row["unit"]),
|
|
236
|
+
tax_type: Payload::TAX_TYPE.invert[row["tax_type"].to_s],
|
|
237
|
+
remark: presence(row["remark"])
|
|
238
|
+
)
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
# Keep whole numbers integral.
|
|
242
|
+
def numeric(value)
|
|
243
|
+
rational = value.to_s.to_r
|
|
244
|
+
rational.denominator == 1 ? rational.to_i : rational.to_f
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
def presence(value)
|
|
248
|
+
string = value.to_s
|
|
249
|
+
string.empty? ? nil : string
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
def unix_time(value)
|
|
253
|
+
seconds = Integer(value.to_s, exception: false)
|
|
254
|
+
seconds && Time.at(seconds).getlocal("+08:00")
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
# "20221201" and "09:56:38" (UTC+8) → Time, or nil without a date.
|
|
258
|
+
def taipei_time(date, time)
|
|
259
|
+
match = /\A(\d{4})(\d{2})(\d{2})\z/.match(date.to_s)
|
|
260
|
+
return nil unless match
|
|
261
|
+
|
|
262
|
+
hour, minute, second = time.to_s.split(":").map(&:to_i)
|
|
263
|
+
Time.new(*match.captures.map(&:to_i), hour.to_i, minute.to_i, second.to_i, "+08:00")
|
|
264
|
+
end
|
|
265
|
+
end
|
|
266
|
+
end
|
|
267
|
+
end
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "einvoice"
|
|
4
|
+
require "einvoice/amego/errors"
|
|
5
|
+
require "einvoice/amego/client"
|
|
6
|
+
require "einvoice/amego/payload"
|
|
7
|
+
require "einvoice/amego/provider"
|
|
8
|
+
|
|
9
|
+
module Einvoice
|
|
10
|
+
# Adapter for Amego 光貿科技's JSON e-invoice API.
|
|
11
|
+
#
|
|
12
|
+
# The wire format is a form POST with a JSON +data+ field and an MD5 +sign+.
|
|
13
|
+
# There is no encryption. None of that reaches application code: {Provider}
|
|
14
|
+
# exposes only the unified model.
|
|
15
|
+
#
|
|
16
|
+
# provider = Einvoice::Amego::Provider.new(**Einvoice::Amego::SANDBOX)
|
|
17
|
+
# provider.issue(order_id: "ORDER_1", ...) # => Einvoice::IssueInvoiceResult
|
|
18
|
+
module Amego
|
|
19
|
+
# Amego's published shared **test** account. Every developer uses it, so
|
|
20
|
+
# never use it for anything real. Amego has one host for test and
|
|
21
|
+
# production: these credentials are what make a call a test.
|
|
22
|
+
SANDBOX = {
|
|
23
|
+
ban: "12345678",
|
|
24
|
+
app_key: "sHeq7t8G1wiQvhAuIM27"
|
|
25
|
+
}.freeze
|
|
26
|
+
end
|
|
27
|
+
end
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
# Feature flags a provider may or may not support. Every adapter declares its
|
|
5
|
+
# own set so callers feature-detect at runtime ({Capability::Support#supports?})
|
|
6
|
+
# instead of discovering a gap only when a request fails.
|
|
7
|
+
#
|
|
8
|
+
# The five core operations are listed so a degraded/partial adapter can be
|
|
9
|
+
# honest about what it omits; the rest cover optional behaviour that genuinely
|
|
10
|
+
# differs between value-added centers.
|
|
11
|
+
module Capability
|
|
12
|
+
# 開立發票.
|
|
13
|
+
ISSUE = :issue
|
|
14
|
+
# 作廢發票.
|
|
15
|
+
VOID = :void
|
|
16
|
+
# 開立折讓.
|
|
17
|
+
ALLOWANCE = :allowance
|
|
18
|
+
# 作廢折讓.
|
|
19
|
+
VOID_ALLOWANCE = :void_allowance
|
|
20
|
+
# 查詢發票.
|
|
21
|
+
QUERY = :query
|
|
22
|
+
# Issue to a business buyer with a 統一編號 (B2B).
|
|
23
|
+
B2B = :b2b
|
|
24
|
+
# Mixed tax-rate invoice (應稅 + 零稅率 + 免稅 in one document).
|
|
25
|
+
MIXED_TAX = :mixed_tax
|
|
26
|
+
# Look up an invoice by the merchant order id, not just the invoice number.
|
|
27
|
+
QUERY_BY_ORDER_ID = :query_by_order_id
|
|
28
|
+
# Schedule an invoice to be issued automatically at a future date. No
|
|
29
|
+
# adapter declares it and the unified model has no method for it yet: at
|
|
30
|
+
# ECPay a delayed issue calls the merchant back, and 2.0 has no callbacks.
|
|
31
|
+
# It stays so that a later version can add the feature.
|
|
32
|
+
SCHEDULED_ISSUE = :scheduled_issue
|
|
33
|
+
# Validate a carrier (手機條碼 / 愛心碼) against the tax authority.
|
|
34
|
+
CARRIER_VALIDATION = :carrier_validation
|
|
35
|
+
# Annotate a foreign-currency sale via currency + exchange_rate. Statutory
|
|
36
|
+
# amounts are still filed in integer TWD; providers that don't support it
|
|
37
|
+
# reject a non-TWD currency instead of silently dropping it.
|
|
38
|
+
FOREIGN_CURRENCY = :foreign_currency
|
|
39
|
+
|
|
40
|
+
ALL = [
|
|
41
|
+
ISSUE, VOID, ALLOWANCE, VOID_ALLOWANCE, QUERY, B2B, MIXED_TAX,
|
|
42
|
+
QUERY_BY_ORDER_ID, SCHEDULED_ISSUE, CARRIER_VALIDATION, FOREIGN_CURRENCY
|
|
43
|
+
].freeze
|
|
44
|
+
|
|
45
|
+
# Mixed into anything that exposes a +#capabilities+ set and a +#name+.
|
|
46
|
+
module Support
|
|
47
|
+
# The MIG filing currency. Anything else needs FOREIGN_CURRENCY.
|
|
48
|
+
TWD = "TWD"
|
|
49
|
+
|
|
50
|
+
# Whether this provider declares support for +capability+.
|
|
51
|
+
def supports?(capability)
|
|
52
|
+
capabilities.include?(capability)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Raise {UnsupportedError} unless this provider supports +capability+.
|
|
56
|
+
def assert_supports!(capability)
|
|
57
|
+
return if supports?(capability)
|
|
58
|
+
|
|
59
|
+
raise Einvoice::UnsupportedError.new(
|
|
60
|
+
%(Provider "#{name}" does not support capability "#{capability}"),
|
|
61
|
+
provider: name
|
|
62
|
+
)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# Statutory amounts are always filed in TWD, so a +currency+ is an
|
|
66
|
+
# annotation of the original sale that only some centers can carry. Every
|
|
67
|
+
# adapter owes the caller the same answer here — refuse rather than file a
|
|
68
|
+
# foreign-currency sale as though it were TWD — so the check lives once.
|
|
69
|
+
#
|
|
70
|
+
# It belongs to the provider rather than to {Input}, which knows a provider
|
|
71
|
+
# only by name and has no capability set to consult.
|
|
72
|
+
def assert_currency_supported!(currency)
|
|
73
|
+
return if currency.nil? || currency == TWD
|
|
74
|
+
|
|
75
|
+
assert_supports!(Capability::FOREIGN_CURRENCY)
|
|
76
|
+
end
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|