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,494 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
# Coerces a plain Hash (symbol- or string-keyed — e.g. a JSON fixture) into the
|
|
5
|
+
# immutable value types, validating as it goes and raising
|
|
6
|
+
# {ValidationError} on bad input. Adapters call these before mapping to their
|
|
7
|
+
# wire format, so a malformed request fails the same way everywhere and never
|
|
8
|
+
# reaches the network.
|
|
9
|
+
#
|
|
10
|
+
# A value object built with +.new+ goes through the same checks as a Hash:
|
|
11
|
+
# Input turns it back into a Hash first. So whatever an adapter gets from
|
|
12
|
+
# Input has passed every check, however the caller built it.
|
|
13
|
+
#
|
|
14
|
+
# Enum fields accept either the canonical symbol (+:taxable+) or a wire-style
|
|
15
|
+
# string (+"TAXABLE"+, any case) — the bridge that lets the Ruby SDK consume
|
|
16
|
+
# the same language-neutral fixtures as the TypeScript one.
|
|
17
|
+
#
|
|
18
|
+
# Deliberately dependency-free: a small hand-written validator, not a schema
|
|
19
|
+
# library, keeping the core's runtime dependencies at zero.
|
|
20
|
+
module Input
|
|
21
|
+
# 統一編號 [mig 表 4-7].
|
|
22
|
+
UBN_FORMAT = /\A\d{8}\z/
|
|
23
|
+
# 手機條碼: "/" and 7 of 0-9 A-Z . + -. 自然人憑證: 2 letters and 14 digits.
|
|
24
|
+
CARRIER_FORMATS = {
|
|
25
|
+
CarrierType::MOBILE_BARCODE => %r{\A/[0-9A-Z.+-]{7}\z},
|
|
26
|
+
CarrierType::CITIZEN_CERTIFICATE => /\A[A-Z]{2}\d{14}\z/
|
|
27
|
+
}.freeze
|
|
28
|
+
# MIG F0501 and G0501 allow a reason of 1 to 20 characters.
|
|
29
|
+
MAX_REASON_LENGTH = 20
|
|
30
|
+
# MIG 4.1 field lengths, checked here once so that every provider gets the
|
|
31
|
+
# same answer [mig 表 4-2, 15-2, 15-5, 18-2]. A shorter limit of one
|
|
32
|
+
# provider is that adapter's UnsupportedError.
|
|
33
|
+
MIG_LENGTHS = {
|
|
34
|
+
remark: 200, buyer_name: 60, buyer_address: 100, buyer_email: 400, buyer_phone: 26,
|
|
35
|
+
carrier_code: 400, item_description: 500, item_unit: 6, item_remark: 120
|
|
36
|
+
}.freeze
|
|
37
|
+
# MIG 表 4-2: a consumer's name must not be 0 to 0000.
|
|
38
|
+
ZERO_NAME = /\A0{1,4}\z/
|
|
39
|
+
# MIG CustomsClearanceMarkEnum and ZeroTaxRateReasonEnum [mig 表 4-9, 4-19].
|
|
40
|
+
CUSTOMS_CLEARANCE_MARKS = %w[1 2].freeze
|
|
41
|
+
ZERO_TAX_RATE_REASONS = ("71".."79").to_a.freeze
|
|
42
|
+
DEFAULT_VOID_ALLOWANCE_REASON = "作廢折讓"
|
|
43
|
+
# The rates the MIG allows [mig 表 4-18].
|
|
44
|
+
TAX_RATES = [0, Rational(1, 100), Rational(2, 100), Rational(5, 100), Rational(15, 100),
|
|
45
|
+
Rational(25, 100)].freeze
|
|
46
|
+
STANDARD_TAX_RATE = Rational(5, 100)
|
|
47
|
+
# A reference or an allowance can describe a mixed-tax invoice.
|
|
48
|
+
REFERENCE_TAX_TYPES = (TaxType::ALL + [TaxType::MIXED]).freeze
|
|
49
|
+
|
|
50
|
+
module_function
|
|
51
|
+
|
|
52
|
+
def issue(input, provider: nil)
|
|
53
|
+
h = hash!(unbuild(input), "input", provider)
|
|
54
|
+
items = build_items(h[:items], provider)
|
|
55
|
+
amount = build_amount(h[:amount], provider)
|
|
56
|
+
buyer = build_buyer(h[:buyer], provider)
|
|
57
|
+
tax_type = enum!(h[:tax_type], TaxType::ALL, :tax_type, provider)
|
|
58
|
+
category = h[:category] && enum!(h[:category], InvoiceCategory::ALL, :category, provider)
|
|
59
|
+
check_category!(category, buyer, provider)
|
|
60
|
+
check_consumer_name!(category, buyer, provider)
|
|
61
|
+
parsed = IssueInvoiceInput.new(
|
|
62
|
+
order_id: fetch!(h, :order_id, provider),
|
|
63
|
+
buyer: buyer,
|
|
64
|
+
items: items,
|
|
65
|
+
amount: amount,
|
|
66
|
+
tax_type: tax_type,
|
|
67
|
+
price_mode: enum!(h[:price_mode], PriceMode::ALL, :price_mode, provider),
|
|
68
|
+
tax_rate: tax_rate!(h[:tax_rate], items, tax_type, provider),
|
|
69
|
+
category: category,
|
|
70
|
+
carrier: build_carrier(h[:carrier], provider),
|
|
71
|
+
donation: build_donation(h[:donation], provider),
|
|
72
|
+
remark: length!(h[:remark], :remark, provider),
|
|
73
|
+
currency: h[:currency],
|
|
74
|
+
exchange_rate: h[:exchange_rate],
|
|
75
|
+
customs_clearance_mark: code!(h[:customs_clearance_mark], CUSTOMS_CLEARANCE_MARKS,
|
|
76
|
+
:customs_clearance_mark, provider),
|
|
77
|
+
zero_tax_rate_reason: code!(h[:zero_tax_rate_reason], ZERO_TAX_RATE_REASONS,
|
|
78
|
+
:zero_tax_rate_reason, provider),
|
|
79
|
+
provider_options: h[:provider_options]
|
|
80
|
+
)
|
|
81
|
+
if parsed.amount.nil?
|
|
82
|
+
parsed = parsed.with(amount: issue_amount(parsed, provider))
|
|
83
|
+
else
|
|
84
|
+
check_issue_amount!(parsed, provider)
|
|
85
|
+
end
|
|
86
|
+
check_zero_rated!(parsed, provider)
|
|
87
|
+
parsed
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def void(input, provider: nil)
|
|
91
|
+
h = hash!(unbuild(input), "input", provider)
|
|
92
|
+
VoidInvoiceInput.new(
|
|
93
|
+
invoice: invoice_reference!(h[:invoice], provider, need_number: true),
|
|
94
|
+
reason: reason!(fetch!(h, :reason, provider), provider),
|
|
95
|
+
provider_options: h[:provider_options]
|
|
96
|
+
)
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# The tax type and rate come from the input, else from the invoice
|
|
100
|
+
# reference. There is no default: an allowance taxed at the wrong rate is a
|
|
101
|
+
# wrong filing. An allowance with no taxed line has rate 0.
|
|
102
|
+
def allowance(input, provider: nil)
|
|
103
|
+
h = hash!(unbuild(input), "input", provider)
|
|
104
|
+
invoice = invoice_reference!(h[:invoice], provider, need_number: true)
|
|
105
|
+
tax_type = h[:tax_type] ? enum!(h[:tax_type], REFERENCE_TAX_TYPES, :tax_type, provider) : invoice.tax_type
|
|
106
|
+
fail!("tax_type is required, or invoice.tax_type in the reference", provider) if tax_type.nil?
|
|
107
|
+
|
|
108
|
+
items = build_items(h[:items], provider)
|
|
109
|
+
check_not_negative!(items, provider)
|
|
110
|
+
tax_rate = h[:tax_rate].nil? ? invoice.tax_rate : mig_rate!(h[:tax_rate], "tax_rate", provider)
|
|
111
|
+
tax_rate ||= 0r if items.none? { |item| TaxType::TAXED.include?(item.tax_type || tax_type) }
|
|
112
|
+
fail!("tax_rate is required, or invoice.tax_rate in the reference", provider) if tax_rate.nil?
|
|
113
|
+
|
|
114
|
+
parsed = AllowanceInput.new(
|
|
115
|
+
invoice: invoice,
|
|
116
|
+
allowance_id: fetch!(h, :allowance_id, provider),
|
|
117
|
+
items: items,
|
|
118
|
+
amount: build_amount(h[:amount], provider),
|
|
119
|
+
price_mode: enum!(h[:price_mode], PriceMode::ALL, :price_mode, provider),
|
|
120
|
+
tax_type: tax_type,
|
|
121
|
+
tax_rate: tax_rate,
|
|
122
|
+
provider_options: h[:provider_options]
|
|
123
|
+
)
|
|
124
|
+
if parsed.amount.nil?
|
|
125
|
+
parsed = parsed.with(amount: allowance_amount(parsed, provider))
|
|
126
|
+
else
|
|
127
|
+
check_allowance_amount!(parsed, provider)
|
|
128
|
+
end
|
|
129
|
+
parsed
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def void_allowance(input, provider: nil)
|
|
133
|
+
h = hash!(unbuild(input), "input", provider)
|
|
134
|
+
VoidAllowanceInput.new(
|
|
135
|
+
allowance: allowance_reference!(h[:allowance], provider),
|
|
136
|
+
reason: reason!(blank?(h[:reason]) ? DEFAULT_VOID_ALLOWANCE_REASON : h[:reason], provider),
|
|
137
|
+
provider_options: h[:provider_options]
|
|
138
|
+
)
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def query(input, provider: nil)
|
|
142
|
+
h = hash!(unbuild(input), "input", provider)
|
|
143
|
+
invoice = invoice_reference!(h[:invoice], provider, need_number: false)
|
|
144
|
+
if blank?(invoice.number) && blank?(invoice.order_id)
|
|
145
|
+
fail!("query needs invoice.number or invoice.order_id", provider)
|
|
146
|
+
end
|
|
147
|
+
QueryInvoiceInput.new(invoice: invoice, provider_options: h[:provider_options])
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# A carrier on its own, for Provider#validate_carrier.
|
|
151
|
+
def carrier(input, provider: nil)
|
|
152
|
+
fail!("carrier is required", provider) if input.nil?
|
|
153
|
+
|
|
154
|
+
build_carrier(unbuild(input), provider)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# A value object back to the Hash it came from, all the way down, so it
|
|
158
|
+
# takes the same path through the checks as a Hash. A reference becomes
|
|
159
|
+
# its stored form (#to_h).
|
|
160
|
+
def unbuild(value)
|
|
161
|
+
case value
|
|
162
|
+
when InvoiceReference, AllowanceReference then value.to_h
|
|
163
|
+
when Data then value.to_h.transform_values { |field| unbuild(field) }
|
|
164
|
+
when Hash then value.transform_values { |field| unbuild(field) }
|
|
165
|
+
when Array then value.map { |item| unbuild(item) }
|
|
166
|
+
else value
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# --- amounts ---------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
# The items decide the totals. An invoice follows F0401: for a consumer the
|
|
173
|
+
# tax is inside sales_amount and tax_amount is 0, for a business it is apart.
|
|
174
|
+
# Either way the tax is round(taxable sales × tax_rate), so the same input
|
|
175
|
+
# gets the same tax at every provider.
|
|
176
|
+
def check_issue_amount!(input, provider)
|
|
177
|
+
breakdown = input.tax_breakdown(provider: provider)
|
|
178
|
+
amount = input.amount
|
|
179
|
+
check_total!(amount, breakdown, provider)
|
|
180
|
+
if input.resolved_category == InvoiceCategory::B2B
|
|
181
|
+
check_tax!(amount, breakdown, input.tax_rate, provider)
|
|
182
|
+
elsif !amount.tax_amount.zero?
|
|
183
|
+
fail!("a B2C invoice has tax_amount 0 and the tax inside sales_amount (F0401), got tax_amount " \
|
|
184
|
+
"#{amount.tax_amount}", provider)
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# The totals that the core derives when the caller gives no +amount+, by
|
|
189
|
+
# the same rules that check a given one: F0401 for an invoice, G0401 for an
|
|
190
|
+
# allowance.
|
|
191
|
+
def issue_amount(input, provider)
|
|
192
|
+
breakdown = input.tax_breakdown(provider: provider)
|
|
193
|
+
total = breakdown.total_amount
|
|
194
|
+
tax = input.resolved_category == InvoiceCategory::B2B ? breakdown.tax_amount : 0
|
|
195
|
+
totals = { sales_amount: total - tax, tax_amount: tax, total_amount: total }
|
|
196
|
+
# Discount lines can take the items below zero. A given amount cannot be
|
|
197
|
+
# negative, so a derived one cannot be either.
|
|
198
|
+
totals.each do |field, value|
|
|
199
|
+
fail!("amount.#{field} must not be negative, got #{value}", provider) if value.negative?
|
|
200
|
+
end
|
|
201
|
+
AmountSummary.new(**totals)
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
def allowance_amount(input, provider)
|
|
205
|
+
breakdown = input.tax_breakdown(provider: provider)
|
|
206
|
+
AmountSummary.new(sales_amount: breakdown.total_amount - breakdown.tax_amount,
|
|
207
|
+
tax_amount: breakdown.tax_amount, total_amount: breakdown.total_amount)
|
|
208
|
+
end
|
|
209
|
+
|
|
210
|
+
# An allowance follows G0401: sales_amount excludes tax.
|
|
211
|
+
def check_allowance_amount!(input, provider)
|
|
212
|
+
breakdown = input.tax_breakdown(provider: provider)
|
|
213
|
+
check_total!(input.amount, breakdown, provider)
|
|
214
|
+
check_tax!(input.amount, breakdown, input.tax_rate, provider)
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
def check_total!(amount, breakdown, provider)
|
|
218
|
+
return if amount.total_amount == breakdown.total_amount
|
|
219
|
+
|
|
220
|
+
fail!("total_amount is #{amount.total_amount}, but the items add up to #{breakdown.total_amount} " \
|
|
221
|
+
"with tax", provider)
|
|
222
|
+
end
|
|
223
|
+
|
|
224
|
+
def check_tax!(amount, breakdown, rate, provider)
|
|
225
|
+
return if amount.tax_amount == breakdown.tax_amount
|
|
226
|
+
|
|
227
|
+
fail!("tax_amount is #{amount.tax_amount}, but the tax of the items is #{breakdown.tax_amount} " \
|
|
228
|
+
"(taxable #{breakdown.taxable_amount} at #{Number.plain(rate.to_r)})", provider)
|
|
229
|
+
end
|
|
230
|
+
|
|
231
|
+
# --- references ------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
# An InvoiceReference, a Hash of its fields, or a plain invoice number.
|
|
234
|
+
def invoice_reference!(value, provider, need_number:)
|
|
235
|
+
fail!("invoice is required", provider) if blank?(value)
|
|
236
|
+
|
|
237
|
+
reference = if value.is_a?(String)
|
|
238
|
+
InvoiceReference.new(number: value)
|
|
239
|
+
else
|
|
240
|
+
build_invoice_reference(hash!(value, "invoice", provider), provider)
|
|
241
|
+
end
|
|
242
|
+
fail!("invoice.number is required", provider) if need_number && blank?(reference.number)
|
|
243
|
+
reference
|
|
244
|
+
end
|
|
245
|
+
|
|
246
|
+
def build_invoice_reference(h, provider)
|
|
247
|
+
ubn = blank?(h[:buyer_ubn]) ? nil : h[:buyer_ubn].to_s
|
|
248
|
+
fail!("invoice.buyer_ubn must be 8 digits, got #{ubn.inspect}", provider) if ubn && !ubn.match?(UBN_FORMAT)
|
|
249
|
+
|
|
250
|
+
InvoiceReference.new(
|
|
251
|
+
number: presence(h[:number]),
|
|
252
|
+
invoice_datetime: h[:invoice_datetime] &&
|
|
253
|
+
Taipei.time(h[:invoice_datetime], field: "invoice.invoice_datetime", provider: provider),
|
|
254
|
+
random_code: presence(h[:random_code]),
|
|
255
|
+
order_id: presence(h[:order_id]),
|
|
256
|
+
total_amount: h[:total_amount] && Number.integer!(h[:total_amount], field: "invoice.total_amount",
|
|
257
|
+
provider: provider),
|
|
258
|
+
buyer_ubn: ubn,
|
|
259
|
+
tax_type: h[:tax_type] && enum!(h[:tax_type], REFERENCE_TAX_TYPES, :"invoice.tax_type", provider),
|
|
260
|
+
tax_rate: h[:tax_rate].nil? ? nil : mig_rate!(h[:tax_rate], "invoice.tax_rate", provider)
|
|
261
|
+
)
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
# An AllowanceReference, a Hash of its fields, or a plain allowance number.
|
|
265
|
+
def allowance_reference!(value, provider)
|
|
266
|
+
fail!("allowance is required", provider) if blank?(value)
|
|
267
|
+
return AllowanceReference.new(allowance_number: value) if value.is_a?(String)
|
|
268
|
+
|
|
269
|
+
h = hash!(value, "allowance", provider)
|
|
270
|
+
AllowanceReference.new(
|
|
271
|
+
allowance_number: fetch!(h, :allowance_number, provider),
|
|
272
|
+
allowance_date: h[:allowance_date] &&
|
|
273
|
+
Taipei.date(h[:allowance_date], field: "allowance.allowance_date", provider: provider),
|
|
274
|
+
invoice_number: presence(h[:invoice_number])
|
|
275
|
+
)
|
|
276
|
+
end
|
|
277
|
+
|
|
278
|
+
def presence(value)
|
|
279
|
+
blank?(value) ? nil : value
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
# --- builders --------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
def build_buyer(value, provider)
|
|
285
|
+
return nil if value.nil?
|
|
286
|
+
|
|
287
|
+
h = hash!(value, "buyer", provider)
|
|
288
|
+
ubn = blank?(h[:ubn]) ? nil : h[:ubn].to_s
|
|
289
|
+
fail!("buyer ubn must be 8 digits, got #{ubn.inspect}", provider) if ubn && !ubn.match?(UBN_FORMAT)
|
|
290
|
+
|
|
291
|
+
Buyer.new(name: length!(h[:name], :buyer_name, provider), ubn: ubn,
|
|
292
|
+
email: length!(h[:email], :buyer_email, provider),
|
|
293
|
+
address: length!(h[:address], :buyer_address, provider),
|
|
294
|
+
phone: length!(h[:phone], :buyer_phone, provider))
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
def build_carrier(value, provider)
|
|
298
|
+
return nil if value.nil?
|
|
299
|
+
|
|
300
|
+
h = hash!(value, "carrier", provider)
|
|
301
|
+
type = enum!(h[:type], CarrierType::ALL, :carrier_type, provider)
|
|
302
|
+
format = CARRIER_FORMATS[type]
|
|
303
|
+
if format && !h[:code].to_s.match?(format)
|
|
304
|
+
fail!("carrier code for #{type} must match #{format.source}, got #{h[:code].inspect}", provider)
|
|
305
|
+
end
|
|
306
|
+
# MIG 表 15-3: no space, half-width or full-width, at either end.
|
|
307
|
+
if h[:code].to_s.match?(/\A[\s\u3000]|[\s\u3000]\z/)
|
|
308
|
+
fail!("carrier code must not start or end with a space, got #{h[:code].inspect}", provider)
|
|
309
|
+
end
|
|
310
|
+
Carrier.new(type: type, code: length!(h[:code], :carrier_code, provider))
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
def build_donation(value, provider)
|
|
314
|
+
return nil if value.nil?
|
|
315
|
+
|
|
316
|
+
# Kept as a String: a 愛心碼 is an identifier, not a number, and real ones
|
|
317
|
+
# carry a leading zero (0096) that an integer round-trip would destroy.
|
|
318
|
+
npoban = fetch!(hash!(value, "donation", provider), :npoban, provider).to_s
|
|
319
|
+
unless npoban.match?(Donation::CODE_FORMAT)
|
|
320
|
+
fail!("npoban must be 3–7 digits (愛心碼), got #{npoban.inspect}", provider)
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
Donation.new(npoban: npoban)
|
|
324
|
+
end
|
|
325
|
+
|
|
326
|
+
# nil when the caller gives no amount: the core derives it from the items.
|
|
327
|
+
def build_amount(value, provider)
|
|
328
|
+
return nil if value.nil?
|
|
329
|
+
|
|
330
|
+
h = hash!(value, "amount", provider)
|
|
331
|
+
sales, tax, total = %i[sales_amount tax_amount total_amount].map do |field|
|
|
332
|
+
value = Number.integer!(h[field], field: "amount.#{field}", provider: provider)
|
|
333
|
+
fail!("amount.#{field} must not be negative, got #{value}", provider) if value.negative?
|
|
334
|
+
value
|
|
335
|
+
end
|
|
336
|
+
unless sales + tax == total
|
|
337
|
+
fail!("amount total #{total} != sales #{sales} + tax #{tax}", provider)
|
|
338
|
+
end
|
|
339
|
+
AmountSummary.new(sales_amount: sales, tax_amount: tax, total_amount: total)
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
def build_items(value, provider)
|
|
343
|
+
fail!("items must be a non-empty array", provider) unless value.is_a?(Array) && !value.empty?
|
|
344
|
+
|
|
345
|
+
value.each_with_index.map do |item, index|
|
|
346
|
+
h = hash!(item, "items[#{index}]", provider)
|
|
347
|
+
%i[quantity unit_price amount].each do |field|
|
|
348
|
+
Number.decimal!(fetch!(h, field, provider), field: "items[#{index}].#{field}", provider: provider)
|
|
349
|
+
end
|
|
350
|
+
InvoiceItem.new(
|
|
351
|
+
description: length!(fetch!(h, :description, provider), :item_description, provider),
|
|
352
|
+
quantity: fetch!(h, :quantity, provider),
|
|
353
|
+
unit_price: fetch!(h, :unit_price, provider),
|
|
354
|
+
amount: fetch!(h, :amount, provider),
|
|
355
|
+
unit: length!(h[:unit], :item_unit, provider),
|
|
356
|
+
tax_type: h[:tax_type] && enum!(h[:tax_type], TaxType::ALL, :tax_type, provider),
|
|
357
|
+
remark: length!(h[:remark], :item_remark, provider)
|
|
358
|
+
)
|
|
359
|
+
end
|
|
360
|
+
end
|
|
361
|
+
|
|
362
|
+
# --- checks ----------------------------------------------------------------
|
|
363
|
+
|
|
364
|
+
# MIG 4.1 does not allow a negative amount on an allowance. An invoice may
|
|
365
|
+
# have a negative discount line, so build_items does not check this.
|
|
366
|
+
def check_not_negative!(items, provider)
|
|
367
|
+
items.each_with_index do |item, index|
|
|
368
|
+
%i[amount quantity unit_price].each do |field|
|
|
369
|
+
value = Number.decimal!(item.public_send(field), field: "items[#{index}].#{field}", provider: provider)
|
|
370
|
+
fail!("items[#{index}].#{field} must not be negative, got #{item.public_send(field)}", provider) if
|
|
371
|
+
value.negative?
|
|
372
|
+
end
|
|
373
|
+
end
|
|
374
|
+
end
|
|
375
|
+
|
|
376
|
+
# A B2B invoice needs a 統一編號. An explicit category has to agree with it.
|
|
377
|
+
# The value as it is, after a check against its MIG length.
|
|
378
|
+
def length!(value, field, provider)
|
|
379
|
+
limit = MIG_LENGTHS.fetch(field)
|
|
380
|
+
length = value.to_s.length
|
|
381
|
+
fail!("#{field} must be #{limit} characters or fewer (MIG), got #{length}", provider) if length > limit
|
|
382
|
+
value
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
def check_consumer_name!(category, buyer, provider)
|
|
386
|
+
return if buyer.nil? || buyer.business? || category == InvoiceCategory::B2B
|
|
387
|
+
return unless buyer.name.to_s.match?(ZERO_NAME)
|
|
388
|
+
|
|
389
|
+
fail!("a consumer's buyer name must not be #{buyer.name.inspect} (MIG)", provider)
|
|
390
|
+
end
|
|
391
|
+
|
|
392
|
+
def check_category!(category, buyer, provider)
|
|
393
|
+
business = buyer&.business? || false
|
|
394
|
+
if category == InvoiceCategory::B2B && !business
|
|
395
|
+
fail!("a B2B invoice needs buyer.ubn", provider)
|
|
396
|
+
elsif category == InvoiceCategory::B2C && business
|
|
397
|
+
fail!("a B2C invoice cannot carry buyer.ubn #{buyer.ubn}", provider)
|
|
398
|
+
end
|
|
399
|
+
end
|
|
400
|
+
|
|
401
|
+
# A decimal rate that the MIG allows. When none is given, the lines decide,
|
|
402
|
+
# not the header: a taxable line is taxed at 5% under a tax-free header
|
|
403
|
+
# too. A special-tax line has no default: the caller has to give its rate.
|
|
404
|
+
def tax_rate!(value, items, tax_type, provider)
|
|
405
|
+
return mig_rate!(value, "tax_rate", provider) unless value.nil?
|
|
406
|
+
|
|
407
|
+
types = items.map { |item| item.tax_type || tax_type }
|
|
408
|
+
return nil if types.include?(TaxType::SPECIAL)
|
|
409
|
+
|
|
410
|
+
types.include?(TaxType::TAXABLE) ? STANDARD_TAX_RATE : 0r
|
|
411
|
+
end
|
|
412
|
+
|
|
413
|
+
def mig_rate!(value, field, provider)
|
|
414
|
+
rate = Number.decimal!(value, field: field, provider: provider)
|
|
415
|
+
unless TAX_RATES.include?(rate)
|
|
416
|
+
fail!("#{field} must be one of the MIG rates (0, 0.01, 0.02, 0.05, 0.15, 0.25), got #{value.inspect}",
|
|
417
|
+
provider)
|
|
418
|
+
end
|
|
419
|
+
rate
|
|
420
|
+
end
|
|
421
|
+
|
|
422
|
+
# A MIG code given as a String or an Integer. nil when it is not given.
|
|
423
|
+
def code!(value, codes, field, provider)
|
|
424
|
+
return nil if blank?(value)
|
|
425
|
+
|
|
426
|
+
code = value.to_s
|
|
427
|
+
fail!("#{field} must be one of #{codes.join(', ')}, got #{value.inspect}", provider) unless codes.include?(code)
|
|
428
|
+
code
|
|
429
|
+
end
|
|
430
|
+
|
|
431
|
+
# The MIG requires CustomsClearanceMark on a zero-rated invoice. It requires
|
|
432
|
+
# ZeroTaxRateReason too, but ECPay lets a merchant set the reason in its
|
|
433
|
+
# back office, so the core does not ask for it. Amego asks for it itself.
|
|
434
|
+
def check_zero_rated!(parsed, provider)
|
|
435
|
+
return unless parsed.zero_rated? && parsed.customs_clearance_mark.nil?
|
|
436
|
+
|
|
437
|
+
fail!("a zero-rated invoice needs customs_clearance_mark (1 or 2)", provider)
|
|
438
|
+
end
|
|
439
|
+
|
|
440
|
+
def reason!(reason, provider)
|
|
441
|
+
length = reason.to_s.length
|
|
442
|
+
fail!("reason must be #{MAX_REASON_LENGTH} characters or fewer, got #{length}", provider) if length > MAX_REASON_LENGTH
|
|
443
|
+
reason
|
|
444
|
+
end
|
|
445
|
+
|
|
446
|
+
# --- helpers ---------------------------------------------------------------
|
|
447
|
+
|
|
448
|
+
def enum!(value, allowed, field, provider)
|
|
449
|
+
return value if allowed.include?(value)
|
|
450
|
+
|
|
451
|
+
symbol = value.is_a?(String) ? value.downcase.to_sym : nil
|
|
452
|
+
return symbol if symbol && allowed.include?(symbol)
|
|
453
|
+
|
|
454
|
+
fail!("invalid #{field}: #{value.inspect}", provider)
|
|
455
|
+
end
|
|
456
|
+
|
|
457
|
+
# Read a required field, or fail naming it. "Required" means present, not
|
|
458
|
+
# merely non-nil: an empty string is a missing value everywhere in this
|
|
459
|
+
# model, and letting one through only defers the failure to the provider.
|
|
460
|
+
def fetch!(hash, key, provider)
|
|
461
|
+
value = hash[key]
|
|
462
|
+
fail!("#{key} is required", provider) if blank?(value)
|
|
463
|
+
value
|
|
464
|
+
end
|
|
465
|
+
|
|
466
|
+
def blank?(value)
|
|
467
|
+
value.nil? || (value.respond_to?(:empty?) && value.empty?)
|
|
468
|
+
end
|
|
469
|
+
|
|
470
|
+
def fail!(message, provider)
|
|
471
|
+
raise ValidationError.new(message, provider: provider || "einvoice")
|
|
472
|
+
end
|
|
473
|
+
|
|
474
|
+
# Coerce a value that has to be an object, naming the field it came from.
|
|
475
|
+
# Every nested shape goes through here, so a caller who passes a String, an
|
|
476
|
+
# Array or nothing at all gets the same {ValidationError} as any other bad
|
|
477
|
+
# input instead of a NoMethodError raised three frames deeper.
|
|
478
|
+
def hash!(value, field, provider)
|
|
479
|
+
fail!("#{field} must be an object, got #{type_of(value)}", provider) unless value.is_a?(Hash)
|
|
480
|
+
|
|
481
|
+
symbolize_keys(value)
|
|
482
|
+
end
|
|
483
|
+
|
|
484
|
+
# One level deep, which is all the nesting there is: arrays of hashes are
|
|
485
|
+
# handled by the per-item builders, which call back through {hash!}.
|
|
486
|
+
def symbolize_keys(hash)
|
|
487
|
+
hash.each_with_object({}) { |(key, value), out| out[key.to_sym] = value }
|
|
488
|
+
end
|
|
489
|
+
|
|
490
|
+
def type_of(value)
|
|
491
|
+
value.nil? ? "nil" : value.class.name
|
|
492
|
+
end
|
|
493
|
+
end
|
|
494
|
+
end
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "set"
|
|
4
|
+
|
|
5
|
+
module Einvoice
|
|
6
|
+
# In-memory {Provider} for tests and local development. It runs the same input
|
|
7
|
+
# validation as a real adapter (via {Input}) but never hits the network, so
|
|
8
|
+
# application code can be exercised end-to-end without credentials.
|
|
9
|
+
#
|
|
10
|
+
# It mirrors real-adapter behaviour beyond the happy path: capability gating
|
|
11
|
+
# (each operation, and a non-TWD currency, is refused unless its capability
|
|
12
|
+
# is declared), an in-memory state machine (an invoice with an allowance in
|
|
13
|
+
# force cannot be voided, a voided invoice cannot be credited, and voiding
|
|
14
|
+
# its last allowance returns it to issued), and {#fail_next} to inject a
|
|
15
|
+
# one-shot failure for exercising error handling.
|
|
16
|
+
class MockProvider < Provider
|
|
17
|
+
attr_reader :capabilities
|
|
18
|
+
|
|
19
|
+
# @param track [String] the 字軌 prefix (2 letters) for generated numbers
|
|
20
|
+
# @param seq [Integer] deterministic start for generated invoice numbers
|
|
21
|
+
# @param capabilities [Enumerable] restrict declared capabilities to simulate
|
|
22
|
+
# a specific provider profile; defaults to all
|
|
23
|
+
def initialize(track: "MK", seq: 10_000_000, capabilities: Capability::ALL)
|
|
24
|
+
super()
|
|
25
|
+
@track = track
|
|
26
|
+
@seq = seq
|
|
27
|
+
@allowance_seq = 0
|
|
28
|
+
@capabilities = Set.new(capabilities)
|
|
29
|
+
@invoices = {}
|
|
30
|
+
@by_order_id = {}
|
|
31
|
+
# 折讓單號 => { invoice_number:, voided: }
|
|
32
|
+
@allowances = {}
|
|
33
|
+
@queued_failure = nil
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def name
|
|
37
|
+
"mock"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Make the next operation raise +error+, then clear it — for exercising a
|
|
41
|
+
# caller's handling of transport/provider failures the happy path never
|
|
42
|
+
# produces (NETWORK, AUTH, NUMBER_EXHAUSTED, …).
|
|
43
|
+
def fail_next(error)
|
|
44
|
+
@queued_failure = error
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def issue(input)
|
|
48
|
+
check_failure!
|
|
49
|
+
assert_supports!(Capability::ISSUE)
|
|
50
|
+
parsed = Input.issue(input, provider: name)
|
|
51
|
+
assert_currency_supported!(parsed.currency)
|
|
52
|
+
assert_supports!(Capability::B2B) if parsed.resolved_category == InvoiceCategory::B2B
|
|
53
|
+
tax_type = TaxType.of(parsed.items, parsed.tax_type)
|
|
54
|
+
assert_supports!(Capability::MIXED_TAX) if tax_type == TaxType::MIXED
|
|
55
|
+
fail!(ConflictError, "Order id already issued", Reason::DUPLICATE_ORDER) if @by_order_id.key?(parsed.order_id)
|
|
56
|
+
|
|
57
|
+
invoice_number = next_invoice_number
|
|
58
|
+
result = IssueInvoiceResult.new(
|
|
59
|
+
invoice_number: invoice_number,
|
|
60
|
+
invoice_datetime: Taipei.now,
|
|
61
|
+
random_code: format("%04d", (@seq * 7) % 10_000),
|
|
62
|
+
order_id: parsed.order_id,
|
|
63
|
+
total_amount: parsed.amount.total_amount,
|
|
64
|
+
buyer_ubn: parsed.buyer&.ubn,
|
|
65
|
+
tax_type: tax_type,
|
|
66
|
+
tax_rate: parsed.tax_rate,
|
|
67
|
+
status: InvoiceStatus::ISSUED,
|
|
68
|
+
raw: { mock: true }
|
|
69
|
+
)
|
|
70
|
+
@invoices[invoice_number] = { input: parsed, result: result, status: InvoiceStatus::ISSUED }
|
|
71
|
+
@by_order_id[parsed.order_id] = invoice_number
|
|
72
|
+
result
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def void(input)
|
|
76
|
+
check_failure!
|
|
77
|
+
assert_supports!(Capability::VOID)
|
|
78
|
+
parsed = Input.void(input, provider: name)
|
|
79
|
+
stored = require_invoice(parsed.invoice.number)
|
|
80
|
+
fail!(ConflictError, "Invoice already voided", Reason::ALREADY_VOIDED) if
|
|
81
|
+
stored[:status] == InvoiceStatus::VOIDED
|
|
82
|
+
fail!(ConflictError, "Void the invoice's allowances first", Reason::VOID_BLOCKED_BY_ALLOWANCE) if
|
|
83
|
+
allowance_in_force?(parsed.invoice.number)
|
|
84
|
+
|
|
85
|
+
stored[:status] = InvoiceStatus::VOIDED
|
|
86
|
+
VoidInvoiceResult.new(invoice_number: parsed.invoice.number, status: InvoiceStatus::VOIDED,
|
|
87
|
+
cancel_datetime: Taipei.now, raw: { mock: true })
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def allowance(input)
|
|
91
|
+
check_failure!
|
|
92
|
+
assert_supports!(Capability::ALLOWANCE)
|
|
93
|
+
parsed = Input.allowance(input, provider: name)
|
|
94
|
+
stored = require_invoice(parsed.invoice.number)
|
|
95
|
+
# A voided invoice has nothing left to credit. Deliberately not
|
|
96
|
+
# ALREADY_VOIDED: that one means "already in the state you asked for, treat
|
|
97
|
+
# as success", which here would record a refund that never happened.
|
|
98
|
+
fail!(ConflictError, "Cannot credit a voided invoice", Reason::ALLOWANCE_BLOCKED_BY_VOID) if
|
|
99
|
+
stored[:status] == InvoiceStatus::VOIDED
|
|
100
|
+
|
|
101
|
+
stored[:status] = InvoiceStatus::ALLOWANCE
|
|
102
|
+
@allowance_seq += 1
|
|
103
|
+
allowance_number = format("AL%08d", @allowance_seq)
|
|
104
|
+
@allowances[allowance_number] = { invoice_number: parsed.invoice.number, voided: false }
|
|
105
|
+
AllowanceResult.new(
|
|
106
|
+
allowance_number: allowance_number,
|
|
107
|
+
invoice_number: parsed.invoice.number,
|
|
108
|
+
allowance_date: Taipei.today,
|
|
109
|
+
total_amount: parsed.amount.total_amount,
|
|
110
|
+
raw: { mock: true }
|
|
111
|
+
)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def void_allowance(input)
|
|
115
|
+
check_failure!
|
|
116
|
+
assert_supports!(Capability::VOID_ALLOWANCE)
|
|
117
|
+
parsed = Input.void_allowance(input, provider: name)
|
|
118
|
+
allowance_number = parsed.allowance.allowance_number
|
|
119
|
+
allowance = @allowances[allowance_number] || fail!(NotFoundError, "Allowance not found")
|
|
120
|
+
fail!(ConflictError, "Allowance already voided", Reason::ALREADY_VOIDED) if allowance[:voided]
|
|
121
|
+
|
|
122
|
+
allowance[:voided] = true
|
|
123
|
+
invoice_number = allowance[:invoice_number]
|
|
124
|
+
@invoices[invoice_number][:status] = InvoiceStatus::ISSUED unless allowance_in_force?(invoice_number)
|
|
125
|
+
VoidAllowanceResult.new(allowance_number: allowance_number, cancel_datetime: Taipei.now,
|
|
126
|
+
raw: { mock: true })
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def query(input)
|
|
130
|
+
check_failure!
|
|
131
|
+
assert_supports!(Capability::QUERY)
|
|
132
|
+
parsed = Input.query(input, provider: name)
|
|
133
|
+
reference = parsed.invoice
|
|
134
|
+
assert_supports!(Capability::QUERY_BY_ORDER_ID) if reference.number.nil?
|
|
135
|
+
invoice_number = reference.number || @by_order_id[reference.order_id]
|
|
136
|
+
stored = invoice_number && @invoices[invoice_number]
|
|
137
|
+
fail!(NotFoundError, "Invoice not found") unless stored
|
|
138
|
+
|
|
139
|
+
QueryInvoiceResult.new(
|
|
140
|
+
invoice_number: invoice_number,
|
|
141
|
+
invoice_datetime: stored[:result].invoice_datetime,
|
|
142
|
+
random_code: stored[:result].random_code,
|
|
143
|
+
order_id: stored[:input].order_id,
|
|
144
|
+
status: stored[:status],
|
|
145
|
+
amount: stored[:input].amount,
|
|
146
|
+
buyer: stored[:input].buyer,
|
|
147
|
+
items: stored[:input].items,
|
|
148
|
+
tax_type: stored[:result].tax_type,
|
|
149
|
+
tax_rate: stored[:result].tax_rate,
|
|
150
|
+
raw: { mock: true }
|
|
151
|
+
)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# Every well-formed carrier counts as registered.
|
|
155
|
+
def validate_carrier(carrier)
|
|
156
|
+
check_failure!
|
|
157
|
+
assert_supports!(Capability::CARRIER_VALIDATION)
|
|
158
|
+
Input.carrier(carrier, provider: name)
|
|
159
|
+
true
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
private
|
|
163
|
+
|
|
164
|
+
def check_failure!
|
|
165
|
+
return unless @queued_failure
|
|
166
|
+
|
|
167
|
+
error = @queued_failure
|
|
168
|
+
@queued_failure = nil
|
|
169
|
+
raise error
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
def next_invoice_number
|
|
173
|
+
n = @seq
|
|
174
|
+
@seq += 1
|
|
175
|
+
format("%s%08d", @track, n)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def allowance_in_force?(invoice_number)
|
|
179
|
+
@allowances.each_value.any? { |a| a[:invoice_number] == invoice_number && !a[:voided] }
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def require_invoice(invoice_number)
|
|
183
|
+
@invoices[invoice_number] || fail!(NotFoundError, "Invoice not found")
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# One raise site shape, so a missing reason is visible rather than incidental.
|
|
187
|
+
def fail!(error_class, message, reason = nil)
|
|
188
|
+
raise error_class.new(message, provider: name, reason: reason)
|
|
189
|
+
end
|
|
190
|
+
end
|
|
191
|
+
end
|