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.
- checksums.yaml +4 -4
- data/.coderabbit.yaml +6 -8
- data/.github/workflows/build.yml +6 -3
- data/CHANGELOG.md +43 -44
- data/Gemfile +3 -10
- data/README.md +221 -328
- data/README.zh-TW.md +322 -0
- data/Rakefile +2 -51
- data/bin/console +3 -6
- data/einvoice.gemspec +16 -18
- 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 -13
- 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 -9
- metadata +52 -145
- 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 -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,84 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module Amego
|
|
5
|
+
# Maps Amego's +code+ values onto the unified {Einvoice::Error} tree.
|
|
6
|
+
#
|
|
7
|
+
# The codes come from Amego's error code page
|
|
8
|
+
# (https://invoice.amego.tw/info_detail?mid=71). docs/providers/amego/api.md
|
|
9
|
+
# section 6.4 lists them. Codes +15+ and +71+ were seen on the live test
|
|
10
|
+
# account.
|
|
11
|
+
module Errors
|
|
12
|
+
# code => [error class code, Reason or nil]
|
|
13
|
+
CODES = {
|
|
14
|
+
# Common codes.
|
|
15
|
+
10 => [:provider, nil], # system maintenance
|
|
16
|
+
11 => [:auth, Reason::CREDENTIALS_INVALID], # invoice (統一編號) empty
|
|
17
|
+
12 => [:auth, Reason::CREDENTIALS_INVALID], # invoice (統一編號) wrong
|
|
18
|
+
13 => [:auth, Reason::NOT_ENROLLED], # status not active
|
|
19
|
+
14 => [:auth, Reason::IP_BLOCKED],
|
|
20
|
+
15 => [:auth, Reason::STALE_TIMESTAMP], # time out of range
|
|
21
|
+
16 => [:auth, Reason::CREDENTIALS_INVALID], # sign wrong
|
|
22
|
+
17 => [:validation, nil], # data empty
|
|
23
|
+
18 => [:provider, nil], # database connection failed
|
|
24
|
+
19 => [:auth, Reason::ACCOUNT_SUSPENDED],
|
|
25
|
+
20 => [:validation, nil], # data is not JSON
|
|
26
|
+
21 => [:provider, Reason::RATE_LIMITED],
|
|
27
|
+
22 => [:auth, Reason::NOT_ENROLLED], # API access not applied for
|
|
28
|
+
23 => [:validation, nil], # this API takes an array
|
|
29
|
+
51 => [:provider, nil], # past the 180-day query limit
|
|
30
|
+
71 => [:not_found, nil],
|
|
31
|
+
99 => [:provider, nil],
|
|
32
|
+
# f0401
|
|
33
|
+
3_040_111 => [:number_exhausted, nil],
|
|
34
|
+
3_040_132 => [:validation, Reason::CARRIER_NOT_REGISTERED],
|
|
35
|
+
3_040_171 => [:conflict, Reason::DUPLICATE_ORDER],
|
|
36
|
+
3_040_191 => [:number_exhausted, nil],
|
|
37
|
+
# f0501
|
|
38
|
+
3_050_111 => [:validation, nil],
|
|
39
|
+
3_050_113 => [:validation, nil],
|
|
40
|
+
3_050_121 => [:conflict, Reason::RETRY_LATER], # still being issued
|
|
41
|
+
3_050_122 => [:conflict, Reason::ALREADY_VOIDED],
|
|
42
|
+
3_050_123 => [:conflict, nil], # already cancelled (註銷)
|
|
43
|
+
3_050_125 => [:not_found, nil],
|
|
44
|
+
3_050_126 => [:conflict, Reason::PAST_DEADLINE],
|
|
45
|
+
3_050_131 => [:conflict, Reason::RETRY_LATER], # a queued change is waiting
|
|
46
|
+
3_050_141 => [:conflict, Reason::VOID_BLOCKED_BY_ALLOWANCE],
|
|
47
|
+
# g0401
|
|
48
|
+
4_040_145 => [:validation, nil],
|
|
49
|
+
4_040_151 => [:validation, nil],
|
|
50
|
+
4_040_153 => [:conflict, Reason::ALLOWANCE_BLOCKED_BY_VOID],
|
|
51
|
+
4_040_154 => [:conflict, nil], # original invoice cancelled
|
|
52
|
+
4_040_156 => [:not_found, nil],
|
|
53
|
+
4_040_157 => [:validation, nil],
|
|
54
|
+
4_040_161 => [:conflict, Reason::DUPLICATE_ALLOWANCE],
|
|
55
|
+
4_040_171 => [:validation, nil],
|
|
56
|
+
4_040_173 => [:validation, nil],
|
|
57
|
+
# g0501
|
|
58
|
+
4_050_132 => [:conflict, Reason::ALREADY_VOIDED],
|
|
59
|
+
4_050_134 => [:not_found, nil],
|
|
60
|
+
4_050_135 => [:conflict, Reason::PAST_DEADLINE],
|
|
61
|
+
4_050_141 => [:conflict, Reason::RETRY_LATER], # a queued change is waiting
|
|
62
|
+
|
|
63
|
+
9_000_111 => [:validation, nil], # barcode empty
|
|
64
|
+
9_000_112 => [:validation, nil] # barcode format wrong
|
|
65
|
+
}.freeze
|
|
66
|
+
|
|
67
|
+
# The other f0401 codes from 3040101 to 3040199 are field format errors.
|
|
68
|
+
ISSUE_FIELD_ERRORS = (3_040_101..3_040_199)
|
|
69
|
+
|
|
70
|
+
module_function
|
|
71
|
+
|
|
72
|
+
# @return [Array(Symbol, Symbol)] the error class code and the Reason
|
|
73
|
+
# (or nil). Codes outside the table are +:provider+: Amego knows why it
|
|
74
|
+
# refused, and we do not.
|
|
75
|
+
def classify(code)
|
|
76
|
+
code = Integer(code, exception: false)
|
|
77
|
+
return CODES[code] if CODES.key?(code)
|
|
78
|
+
return [:validation, nil] if code && ISSUE_FIELD_ERRORS.cover?(code)
|
|
79
|
+
|
|
80
|
+
[:provider, nil]
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
@@ -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
|