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,366 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "set"
|
|
4
|
+
|
|
5
|
+
module Einvoice
|
|
6
|
+
module Tradevan
|
|
7
|
+
module DefaultAPI
|
|
8
|
+
# The merchant settings that every DEFAULTAPI request carries.
|
|
9
|
+
#
|
|
10
|
+
# +paper_print_mode+ (+0+ to +4+) and +invoice_alarm_mode+ (+0+ to +6+)
|
|
11
|
+
# have no documented meaning, so the adapter does not guess a default. The
|
|
12
|
+
# 1.x README used +0+ and +4+. +member_carrier_type+ is the merchant's own
|
|
13
|
+
# 6-character carrier code, needed only for {CarrierType::MEMBER}.
|
|
14
|
+
Settings = Data.define(:company_un, :org_id, :paper_print_mode, :invoice_alarm_mode,
|
|
15
|
+
:invoice_paper_returned, :allowance_paper_returned,
|
|
16
|
+
:member_carrier_type)
|
|
17
|
+
|
|
18
|
+
# {Einvoice::Provider} over Tradevan 關貿's DEFAULTAPI, the API the 1.x
|
|
19
|
+
# client wraps.
|
|
20
|
+
#
|
|
21
|
+
# **Experimental.** It is ported from the 1.x client, its validators and
|
|
22
|
+
# its README examples. Nobody has run it against the live API, and Tradevan
|
|
23
|
+
# does not publish its docs. Test it against your own account before you
|
|
24
|
+
# rely on it. docs/providers/tradevan/defaultapi.md has the details and the
|
|
25
|
+
# open questions.
|
|
26
|
+
#
|
|
27
|
+
# A void and an allowance need the original invoice's +saleIdentifier+,
|
|
28
|
+
# and an allowance its date. The reference from issue or query has what
|
|
29
|
+
# the adapter needs (docs, section 4.1).
|
|
30
|
+
class Provider < ::Einvoice::Provider
|
|
31
|
+
CAPABILITIES = Set[
|
|
32
|
+
Capability::ISSUE,
|
|
33
|
+
Capability::VOID,
|
|
34
|
+
Capability::ALLOWANCE,
|
|
35
|
+
Capability::VOID_ALLOWANCE,
|
|
36
|
+
Capability::QUERY,
|
|
37
|
+
Capability::B2B
|
|
38
|
+
].freeze
|
|
39
|
+
|
|
40
|
+
API_VERSION = "defaultapi"
|
|
41
|
+
# Only hasAllowance is known. The status codes I and V have no source,
|
|
42
|
+
# so the adapter does not read them (4.4).
|
|
43
|
+
QUERY_STATUSES = [InvoiceStatus::ALLOWANCE].freeze
|
|
44
|
+
|
|
45
|
+
attr_reader :capabilities, :client, :settings
|
|
46
|
+
|
|
47
|
+
def initialize(acnt:, acntp:, key1:, key2:, base_url:, company_un:, org_id:,
|
|
48
|
+
paper_print_mode:, invoice_alarm_mode:, invoice_paper_returned:,
|
|
49
|
+
allowance_paper_returned:, member_carrier_type: nil, timeout: 30,
|
|
50
|
+
validate_payload: true, clock: Time)
|
|
51
|
+
super()
|
|
52
|
+
@client = Client.new(acnt: acnt, acntp: acntp, key1: key1, key2: key2,
|
|
53
|
+
base_url: base_url, timeout: timeout)
|
|
54
|
+
@settings = Settings.new(
|
|
55
|
+
company_un: company_un.to_s, org_id: org_id.to_s,
|
|
56
|
+
paper_print_mode: paper_print_mode.to_s, invoice_alarm_mode: invoice_alarm_mode.to_s,
|
|
57
|
+
invoice_paper_returned: invoice_paper_returned.to_s,
|
|
58
|
+
allowance_paper_returned: allowance_paper_returned.to_s,
|
|
59
|
+
member_carrier_type: member_carrier_type
|
|
60
|
+
)
|
|
61
|
+
@validate_payload = validate_payload
|
|
62
|
+
@clock = clock
|
|
63
|
+
@capabilities = CAPABILITIES
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def name
|
|
67
|
+
Client::PROVIDER
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def query_statuses
|
|
71
|
+
QUERY_STATUSES
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# Tells this adapter apart from a future one for a newer Tradevan API.
|
|
75
|
+
def api_version
|
|
76
|
+
API_VERSION
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# Call any DEFAULTAPI path with raw parameters, for example
|
|
80
|
+
#
|
|
81
|
+
# provider.raw("get/getInvoiceMarkInfo", { companyUn: "…", orgId: "…", … })
|
|
82
|
+
#
|
|
83
|
+
# The encryption and the error mapping are applied as usual. Brace the
|
|
84
|
+
# Hash: an unbraced one is read as keyword arguments.
|
|
85
|
+
def raw(path, params)
|
|
86
|
+
@client.request(path, params)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# 開立發票 (type I).
|
|
90
|
+
def issue(input)
|
|
91
|
+
parsed = Input.issue(input, provider: name)
|
|
92
|
+
assert_currency_supported!(parsed.currency)
|
|
93
|
+
tax_type = TaxType.of(parsed.items, parsed.tax_type)
|
|
94
|
+
assert_supports!(Capability::MIXED_TAX) if tax_type == TaxType::MIXED
|
|
95
|
+
data = Payload.issue(parsed, @settings, Taipei.now(@clock))
|
|
96
|
+
Rules.validate!(Rules.issue_errors(data), "issueData") if @validate_payload
|
|
97
|
+
|
|
98
|
+
result = @client.request("post/issue", { issueData: data })
|
|
99
|
+
@client.check_status!(result, "issueStatus")
|
|
100
|
+
# Tradevan may have issued the invoice, so this is not a refusal. But
|
|
101
|
+
# without a number the reference cannot void or credit it.
|
|
102
|
+
if result["invoiceNumber"].to_s.empty?
|
|
103
|
+
raise ProviderError.new("Tradevan reported the issue as done but returned no invoiceNumber",
|
|
104
|
+
provider: name, raw: result)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
IssueInvoiceResult.new(
|
|
108
|
+
invoice_number: result["invoiceNumber"].to_s,
|
|
109
|
+
invoice_datetime: parse_time(result["invoiceDate"], result["invoiceTime"]),
|
|
110
|
+
random_code: result["checkNumber"].to_s,
|
|
111
|
+
order_id: parsed.order_id,
|
|
112
|
+
total_amount: parsed.amount.total_amount,
|
|
113
|
+
buyer_ubn: parsed.resolved_category == InvoiceCategory::B2B ? parsed.buyer&.ubn : nil,
|
|
114
|
+
tax_type: tax_type,
|
|
115
|
+
tax_rate: parsed.tax_rate,
|
|
116
|
+
status: InvoiceStatus::ISSUED,
|
|
117
|
+
raw: result
|
|
118
|
+
)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# 作廢發票 (cancel type I). DEFAULTAPI has no reason field, so the
|
|
122
|
+
# unified +reason+ is not sent.
|
|
123
|
+
def void(input)
|
|
124
|
+
parsed = Input.void(input, provider: name)
|
|
125
|
+
sale, = original_invoice(parsed, need_date: false)
|
|
126
|
+
data = Payload.void(parsed, @settings, sale)
|
|
127
|
+
Rules.validate!(Rules.void_errors(data), "voidData") if @validate_payload
|
|
128
|
+
|
|
129
|
+
result = @client.request("post/cancel", { voidData: data })
|
|
130
|
+
@client.check_status!(result, "voidStatus")
|
|
131
|
+
VoidInvoiceResult.new(invoice_number: parsed.invoice.number, status: InvoiceStatus::VOIDED,
|
|
132
|
+
raw: result)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# 開立折讓 (issue type A). No source shows the response to type A. The
|
|
136
|
+
# adapter reads +allowanceNumber+, which the type I response also has,
|
|
137
|
+
# and raises {ProviderError} when it is empty. Without +allowanceDate+,
|
|
138
|
+
# the date is today in Taipei, the +transactionDate+ it sent (inferred).
|
|
139
|
+
def allowance(input)
|
|
140
|
+
parsed = Input.allowance(input, provider: name)
|
|
141
|
+
assert_supports!(Capability::MIXED_TAX) if TaxType.of(parsed.items, parsed.tax_type) == TaxType::MIXED
|
|
142
|
+
sale, invoice_date = original_invoice(parsed, need_date: true)
|
|
143
|
+
today = Taipei.today(@clock)
|
|
144
|
+
data = Payload.allowance(parsed, @settings, sale: sale, invoice_date: invoice_date, today: today)
|
|
145
|
+
Rules.validate!(Rules.issue_errors(data), "issueData") if @validate_payload
|
|
146
|
+
|
|
147
|
+
result = @client.request("post/issue", { issueData: data })
|
|
148
|
+
@client.check_status!(result, "issueStatus")
|
|
149
|
+
number = result["allowanceNumber"].to_s
|
|
150
|
+
if number.empty?
|
|
151
|
+
raise ProviderError.new("Tradevan returned no allowanceNumber", provider: name, raw: result)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
AllowanceResult.new(
|
|
155
|
+
allowance_number: number,
|
|
156
|
+
invoice_number: parsed.invoice.number,
|
|
157
|
+
allowance_date: parse_time(result["allowanceDate"], nil)&.to_date || today,
|
|
158
|
+
total_amount: parsed.amount.total_amount,
|
|
159
|
+
raw: result
|
|
160
|
+
)
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# 作廢折讓 (cancel type A). There is no reason field here either.
|
|
164
|
+
def void_allowance(input)
|
|
165
|
+
parsed = Input.void_allowance(input, provider: name)
|
|
166
|
+
data = Payload.void_allowance(parsed, @settings)
|
|
167
|
+
Rules.validate!(Rules.void_errors(data), "voidData") if @validate_payload
|
|
168
|
+
|
|
169
|
+
result = @client.request("post/cancel", { voidData: data })
|
|
170
|
+
@client.check_status!(result, "voidStatus")
|
|
171
|
+
VoidAllowanceResult.new(allowance_number: parsed.allowance.allowance_number, raw: result)
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
# 查詢發票 by invoice number (searchInvoiceDetail).
|
|
175
|
+
#
|
|
176
|
+
# The meaning of the response's +status+ codes (+I+, +V+) is unknown, so
|
|
177
|
+
# the result's +status+ is +ALLOWANCE+ when +hasAllowance+ is +Y+, and
|
|
178
|
+
# +nil+ otherwise. A wrong guess could report a voided invoice as issued.
|
|
179
|
+
# The raw code stays in +raw["status"]+.
|
|
180
|
+
def query(input)
|
|
181
|
+
reference = Input.query(input, provider: name).invoice
|
|
182
|
+
assert_supports!(Capability::QUERY_BY_ORDER_ID) if reference.number.nil?
|
|
183
|
+
search(reference.number)
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
private
|
|
187
|
+
|
|
188
|
+
def search(number)
|
|
189
|
+
build_query_result(detail(number))
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# The searchInvoiceDetail object. The client keeps arrays, which some
|
|
193
|
+
# raw endpoints answer, but this one must be an object.
|
|
194
|
+
def detail(number)
|
|
195
|
+
result = @client.request("get/searchInvoiceDetail", { invoiceNumber: number })
|
|
196
|
+
return result if result.is_a?(Hash)
|
|
197
|
+
|
|
198
|
+
raise ProviderError.new("Tradevan returned an invoice detail that is not an object",
|
|
199
|
+
provider: name, raw: result)
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
# The original invoice's +saleIdentifier+ and, for an allowance, its
|
|
203
|
+
# date (docs, section 4.1): +provider_options[:sale_identifier]+ (for
|
|
204
|
+
# invoices the 1.x client issued), else built from the reference's
|
|
205
|
+
# order id. The date comes from the reference. What is missing comes
|
|
206
|
+
# from a query by number. A failed query is the provider's error, not
|
|
207
|
+
# the invoice's: a NotFoundError would read as "the invoice of this
|
|
208
|
+
# call does not exist".
|
|
209
|
+
def original_invoice(parsed, need_date:)
|
|
210
|
+
reference = parsed.invoice
|
|
211
|
+
sale = string_keys(parsed.provider_options)["sale_identifier"]&.to_s
|
|
212
|
+
sale ||= Payload.sale_identifier(@settings, reference.order_id) if reference.order_id
|
|
213
|
+
date = reference.invoice_datetime && Taipei.date(reference.invoice_datetime)
|
|
214
|
+
return [sale, date] if sale && (date || !need_date)
|
|
215
|
+
|
|
216
|
+
found = lookup(reference.number, need_date: need_date && date.nil?)
|
|
217
|
+
sale ||= found[:sale]
|
|
218
|
+
date ||= found[:date]
|
|
219
|
+
# Only the fields this call needs have to come back.
|
|
220
|
+
missing = [("saleIdentifier" unless sale), ("invoiceDate" if need_date && !date)].compact
|
|
221
|
+
if missing.any?
|
|
222
|
+
raise ProviderError.new("Tradevan needs the invoice's #{missing.join(' and ')}; the invoice found " \
|
|
223
|
+
"lacks it", provider: name, reason: Reason::LOOKUP_FAILED)
|
|
224
|
+
end
|
|
225
|
+
[sale, date]
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
# Reads only what the call needs: a void does not need the date, and an
|
|
229
|
+
# allowance does not need the time. So a bad field that the call does
|
|
230
|
+
# not use cannot stop it.
|
|
231
|
+
def lookup(number, need_date:)
|
|
232
|
+
result = detail(number)
|
|
233
|
+
date = need_date ? parse_time(result["invoiceDate"], nil) : nil
|
|
234
|
+
{ sale: presence(result["saleIdentifier"]), date: date && Taipei.date(date) }
|
|
235
|
+
rescue Error => e
|
|
236
|
+
raise ProviderError.new("Tradevan needs the invoice's saleIdentifier or date; looking them up " \
|
|
237
|
+
"failed: #{e.message}", provider: name, reason: Reason::LOOKUP_FAILED, cause: e)
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
def build_query_result(result)
|
|
241
|
+
items = query_items(result["detailList"])
|
|
242
|
+
tax_type = query_tax_type(items)
|
|
243
|
+
QueryInvoiceResult.new(
|
|
244
|
+
invoice_number: result["invoiceNumber"].to_s,
|
|
245
|
+
invoice_datetime: parse_time(result["invoiceDate"], result["invoiceTime"]),
|
|
246
|
+
random_code: result["checkNumber"].to_s,
|
|
247
|
+
order_id: Payload.order_id_from(@settings, result["saleIdentifier"]),
|
|
248
|
+
status: result["hasAllowance"] == "Y" ? InvoiceStatus::ALLOWANCE : nil,
|
|
249
|
+
amount: AmountSummary.new(sales_amount: total(result, "exclusiveAmount"),
|
|
250
|
+
tax_amount: total(result, "tax"),
|
|
251
|
+
total_amount: total(result, "total")),
|
|
252
|
+
buyer: Buyer.new(name: presence(result["receiverName"]), ubn: nil, email: nil,
|
|
253
|
+
address: presence(result["receiverAddr"]),
|
|
254
|
+
phone: presence(result["receiverPhone"])),
|
|
255
|
+
items: items,
|
|
256
|
+
tax_type: tax_type,
|
|
257
|
+
tax_rate: query_rate(items, tax_type),
|
|
258
|
+
raw: result
|
|
259
|
+
)
|
|
260
|
+
end
|
|
261
|
+
|
|
262
|
+
# Two different known types make MIXED. Otherwise a line with a missing
|
|
263
|
+
# or unknown type leaves the invoice's type unknown: it is not a type
|
|
264
|
+
# of its own.
|
|
265
|
+
def query_tax_type(items)
|
|
266
|
+
known = items.map(&:tax_type).compact.uniq
|
|
267
|
+
return TaxType::MIXED if known.size > 1
|
|
268
|
+
return nil if known.empty? || items.any? { |item| item.tax_type.nil? }
|
|
269
|
+
|
|
270
|
+
known.first
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# DEFAULTAPI has no rate field. A taxable line is at the general rate,
|
|
274
|
+
# the only one its tax letters can carry (6.1). Without a taxable line,
|
|
275
|
+
# MIXED too, the rate is 0. A line with an unknown type could be taxable,
|
|
276
|
+
# so it leaves the rate unknown, even when the type is MIXED.
|
|
277
|
+
def query_rate(items, tax_type)
|
|
278
|
+
return nil if tax_type.nil? || items.any? { |item| item.tax_type.nil? }
|
|
279
|
+
|
|
280
|
+
items.any? { |item| item.tax_type == TaxType::TAXABLE } ? Payload::TAX_RATE : 0r
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
# Checked here, not in +detail+: a void or an allowance lookup reads
|
|
284
|
+
# only the sale identifier and the date, so a bad item list cannot
|
|
285
|
+
# stop it.
|
|
286
|
+
def query_items(list)
|
|
287
|
+
return [] if list.nil?
|
|
288
|
+
unless list.is_a?(Array) && list.all?(Hash)
|
|
289
|
+
raise ProviderError.new("Tradevan returned a detailList that is not a list of objects",
|
|
290
|
+
provider: name, raw: list)
|
|
291
|
+
end
|
|
292
|
+
|
|
293
|
+
list.map { |row| build_item(row) }
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
def build_item(row)
|
|
297
|
+
InvoiceItem.new(
|
|
298
|
+
description: row["productName"].to_s,
|
|
299
|
+
quantity: numeric(row, "qty"),
|
|
300
|
+
unit_price: numeric(row, "price"),
|
|
301
|
+
amount: numeric(row, "total"),
|
|
302
|
+
unit: nil,
|
|
303
|
+
tax_type: Payload::TAX_TYPE.invert[row["taxType"].to_s],
|
|
304
|
+
remark: nil
|
|
305
|
+
)
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
# DEFAULTAPI sends numbers as strings. Keep whole numbers integral. A
|
|
309
|
+
# missing number is nil, not 0. A value that is not a decimal number,
|
|
310
|
+
# such as "unavailable" or "5abc", is an error: String#to_r would read
|
|
311
|
+
# it as 0 or 5, a number that Tradevan did not send.
|
|
312
|
+
def numeric(row, field)
|
|
313
|
+
value = row[field].to_s.strip
|
|
314
|
+
return nil if value.empty?
|
|
315
|
+
|
|
316
|
+
rational = decimal!(value, "detailList #{field}", row)
|
|
317
|
+
rational.denominator == 1 ? rational.to_i : rational.to_f
|
|
318
|
+
end
|
|
319
|
+
|
|
320
|
+
# A header total as an Integer. A missing total is 0, as before. A
|
|
321
|
+
# value that is not a decimal number is an error, as in #numeric.
|
|
322
|
+
def total(result, field)
|
|
323
|
+
value = result[field].to_s.strip
|
|
324
|
+
return 0 if value.empty?
|
|
325
|
+
|
|
326
|
+
decimal!(value, field, result).to_i
|
|
327
|
+
end
|
|
328
|
+
|
|
329
|
+
def decimal!(value, field, raw)
|
|
330
|
+
return value.to_r if value.match?(Rules::DECIMAL)
|
|
331
|
+
|
|
332
|
+
raise ProviderError.new("Tradevan returned a #{field} that is not a number: #{value.inspect}",
|
|
333
|
+
provider: name, raw: raw)
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
def string_keys(hash)
|
|
337
|
+
return {} unless hash.is_a?(Hash)
|
|
338
|
+
|
|
339
|
+
hash.to_h { |key, value| [key.to_s, value] }
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
def presence(value)
|
|
343
|
+
string = value.to_s
|
|
344
|
+
string.empty? ? nil : string
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
# "20160425" and "12:34:58" (UTC+8) → Time, or nil when the date is
|
|
348
|
+
# missing, so that a missing date never reads as "now". A date or a
|
|
349
|
+
# time that is there but not valid is the provider's error.
|
|
350
|
+
def parse_time(date, time)
|
|
351
|
+
return nil if date.to_s.empty?
|
|
352
|
+
|
|
353
|
+
year, month, day = /\A(\d{4})(\d{2})(\d{2})\z/.match(date.to_s)&.captures&.map(&:to_i)
|
|
354
|
+
clock = time.to_s.empty? ? "00:00:00" : time.to_s
|
|
355
|
+
hour, minute, second = /\A(\d{2}):(\d{2}):(\d{2})\z/.match(clock)&.captures&.map(&:to_i)
|
|
356
|
+
unless year && hour && Date.valid_date?(year, month, day) && hour < 24 && minute < 60 && second < 60
|
|
357
|
+
raise ProviderError.new("Tradevan returned a date that is not valid: #{date.inspect} #{time.inspect}",
|
|
358
|
+
provider: name)
|
|
359
|
+
end
|
|
360
|
+
|
|
361
|
+
Time.new(year, month, day, hour, minute, second, "+08:00")
|
|
362
|
+
end
|
|
363
|
+
end
|
|
364
|
+
end
|
|
365
|
+
end
|
|
366
|
+
end
|
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module Tradevan
|
|
5
|
+
module DefaultAPI
|
|
6
|
+
# The +issueData+ and +voidData+ field rules, ported from the 1.x
|
|
7
|
+
# validators (+IssueData+, +IssueItem+, +VoidData+ and
|
|
8
|
+
# +issue_data_validator.rb+). Those rules are the only record of the
|
|
9
|
+
# DEFAULTAPI schema, and they ran in production, so they are kept as they
|
|
10
|
+
# were. Two changes:
|
|
11
|
+
#
|
|
12
|
+
# - The 1.x client also checked +donationUnit+ against a bundled list of
|
|
13
|
+
# donation codes. 2.0 has no bundled list. {Einvoice::Input} checks the
|
|
14
|
+
# format, and {Einvoice::MOF::DonationCodes} checks the registry.
|
|
15
|
+
# - A key outside the schema is an error here. Tradevan rejects the whole
|
|
16
|
+
# request when it sees one (PR #38), so it is better to fail before the
|
|
17
|
+
# call.
|
|
18
|
+
#
|
|
19
|
+
# Each check returns a Hash of field name => messages. An empty Hash means
|
|
20
|
+
# the data is valid.
|
|
21
|
+
module Rules
|
|
22
|
+
# A whole decimal string. String#to_r would read "100oops" as 100.
|
|
23
|
+
DECIMAL = /\A-?\d+(\.\d+)?\z/
|
|
24
|
+
|
|
25
|
+
ISSUE_TYPES = %w[I R G H A].freeze
|
|
26
|
+
VOID_TYPES = %w[C I A].freeze
|
|
27
|
+
YES_NO = %w[Y N].freeze
|
|
28
|
+
DATE = /\A\d{8}\z/
|
|
29
|
+
TIME = /\A\d{2}:\d{2}:\d{2}\z/
|
|
30
|
+
|
|
31
|
+
ISSUE_FIELDS = %w[
|
|
32
|
+
companyUn orgId orgUn type saleIdentifier allowanceIdentifier transactionNumber
|
|
33
|
+
transactionDate transactionTime total transactionSource transactionTarget
|
|
34
|
+
invoiceNumber allowanceNumber allowanceDate allowanceExclusiveAmount allowanceTax
|
|
35
|
+
allowancePaperReturned allowanceInclusiveAmount paperPrintMode invoiceAlarmMode
|
|
36
|
+
invoicePaperReturned donate donationUnit carrierType carrierId carrierIdHidden
|
|
37
|
+
buyerUn buyerTitle receiverName receiverAddrZip receiverAddrRoad receiverEmail
|
|
38
|
+
receiverMobile allowaDeclaration idViewId memberId checkNumber invoiceDate
|
|
39
|
+
invoiceTime texclusiveAmount oeclusiveAmount zexclusiveAmount tax mainRemark
|
|
40
|
+
invoiceType itemList
|
|
41
|
+
].freeze
|
|
42
|
+
|
|
43
|
+
ITEM_FIELDS = %w[
|
|
44
|
+
saleIdentifier serialNumber invoiceNumber invoiceDate invoiceTime productCode
|
|
45
|
+
productName qty price tax itemExclude itemTotal taxType description
|
|
46
|
+
].freeze
|
|
47
|
+
|
|
48
|
+
# Fields that carry the caller's input, with a DEFAULTAPI length limit of
|
|
49
|
+
# Tradevan's own: stricter than the MIG's (productName 300 against 500,
|
|
50
|
+
# receiverEmail 80 against 400, receiverMobile 15 against 26, carrierId
|
|
51
|
+
# 64 against 400), or with no MIG field (the order and allowance ids).
|
|
52
|
+
# The core refuses a value over the MIG's limit first, so a value here
|
|
53
|
+
# is over Tradevan's limit only.
|
|
54
|
+
OWN_LIMITS = %w[
|
|
55
|
+
transactionNumber saleIdentifier allowanceIdentifier productName
|
|
56
|
+
receiverEmail receiverMobile carrierId carrierIdHidden
|
|
57
|
+
].freeze
|
|
58
|
+
TOO_LONG = /\Amust be \d+ characters or fewer\z/
|
|
59
|
+
|
|
60
|
+
VOID_FIELDS = %w[
|
|
61
|
+
type saleIdentifier invoiceNumber invoicePaperReturned allowanceNumber
|
|
62
|
+
allowancePaperReturned companyUn
|
|
63
|
+
].freeze
|
|
64
|
+
|
|
65
|
+
module_function
|
|
66
|
+
|
|
67
|
+
# Errors for an +issueData+ Hash (string or symbol keys).
|
|
68
|
+
def issue_errors(data)
|
|
69
|
+
data = stringify(data)
|
|
70
|
+
check = Check.new(data)
|
|
71
|
+
type = data["type"].to_s
|
|
72
|
+
|
|
73
|
+
check.unknown_keys(ISSUE_FIELDS)
|
|
74
|
+
issue_common(check, data)
|
|
75
|
+
issue_by_type(check, data, type)
|
|
76
|
+
issue_items(check, data, type)
|
|
77
|
+
check.errors
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Errors for one +itemList+ entry.
|
|
81
|
+
def item_errors(item)
|
|
82
|
+
item = stringify(item)
|
|
83
|
+
check = Check.new(item)
|
|
84
|
+
check.unknown_keys(ITEM_FIELDS)
|
|
85
|
+
check.required("saleIdentifier", max: 100)
|
|
86
|
+
check.required("serialNumber", is: 4, format: /\A\d+\z/)
|
|
87
|
+
check.optional("invoiceNumber", is: 10)
|
|
88
|
+
check.optional("invoiceDate", is: 8, format: /\A\d+\z/)
|
|
89
|
+
check.optional("invoiceTime", is: 8, format: TIME)
|
|
90
|
+
check.optional("productCode", max: 30)
|
|
91
|
+
check.required("productName", max: 300)
|
|
92
|
+
check.required("qty", max: 20)
|
|
93
|
+
check.required("price", max: 20)
|
|
94
|
+
%w[tax itemExclude itemTotal].each { |field| check.optional(field, max: 20) }
|
|
95
|
+
check.optional("taxType", in: %w[T O Z])
|
|
96
|
+
check.optional("description", max: 300)
|
|
97
|
+
check.errors
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Errors for a +voidData+ Hash.
|
|
101
|
+
def void_errors(data)
|
|
102
|
+
data = stringify(data)
|
|
103
|
+
check = Check.new(data)
|
|
104
|
+
type = data["type"].to_s
|
|
105
|
+
|
|
106
|
+
check.unknown_keys(VOID_FIELDS)
|
|
107
|
+
check.required("type", in: VOID_TYPES)
|
|
108
|
+
if %w[C I].include?(type)
|
|
109
|
+
check.required("saleIdentifier", max: 100)
|
|
110
|
+
check.required("invoiceNumber", is: 10)
|
|
111
|
+
check.required("invoicePaperReturned", in: YES_NO)
|
|
112
|
+
end
|
|
113
|
+
if type == "A"
|
|
114
|
+
check.required("companyUn", is: 8)
|
|
115
|
+
check.required("allowanceNumber", is: 16)
|
|
116
|
+
check.required("allowancePaperReturned", in: YES_NO)
|
|
117
|
+
end
|
|
118
|
+
check.errors
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Raise an error listing every problem, or return +nil+. When every
|
|
122
|
+
# problem is a length over one of Tradevan's own limits, the MIG allows
|
|
123
|
+
# the input, so it is an UnsupportedError (docs/providers/README.md,
|
|
124
|
+
# "The unified model"). Anything else is a ValidationError.
|
|
125
|
+
def validate!(errors, what)
|
|
126
|
+
return if errors.empty?
|
|
127
|
+
|
|
128
|
+
details = errors.flat_map { |field, messages| messages.map { |m| "#{field} #{m}" } }
|
|
129
|
+
if errors.all? { |field, messages| own_limit?(field, messages) }
|
|
130
|
+
raise UnsupportedError.new("Tradevan DEFAULTAPI does not take this #{what} — #{details.join('; ')}",
|
|
131
|
+
provider: Client::PROVIDER, raw_message: details.join("; "))
|
|
132
|
+
end
|
|
133
|
+
raise ValidationError.new("Invalid Tradevan #{what} — #{details.join('; ')}",
|
|
134
|
+
provider: Client::PROVIDER, raw_message: details.join("; "))
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def own_limit?(field, messages)
|
|
138
|
+
OWN_LIMITS.include?(field.sub(/\AitemList\[\d+\]\./, "")) && messages.all?(TOO_LONG)
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def issue_common(check, data)
|
|
142
|
+
check.required("companyUn", is: 8)
|
|
143
|
+
check.required("orgId", is: 5)
|
|
144
|
+
check.optional("orgUn", is: 8)
|
|
145
|
+
check.required("type", in: ISSUE_TYPES)
|
|
146
|
+
check.required("transactionNumber", max: 50)
|
|
147
|
+
check.required("transactionDate", format: DATE)
|
|
148
|
+
check.optional("transactionSource", max: 50)
|
|
149
|
+
check.optional("transactionTarget", max: 50)
|
|
150
|
+
check.required("paperPrintMode", in: %w[0 1 2 3 4])
|
|
151
|
+
check.required("invoiceAlarmMode", in: %w[0 1 2 3 4 5 6])
|
|
152
|
+
check.optional("idViewId", max: 10)
|
|
153
|
+
check.optional("memberId", max: 50)
|
|
154
|
+
|
|
155
|
+
type = data["type"].to_s
|
|
156
|
+
print_mode = data["paperPrintMode"].to_s.to_i
|
|
157
|
+
no_buyer = blank?(data["buyerUn"])
|
|
158
|
+
|
|
159
|
+
if type == "A" || (no_buyer && print_mode != 0)
|
|
160
|
+
check.required("invoicePaperReturned", in: YES_NO)
|
|
161
|
+
end
|
|
162
|
+
if print_mode.zero? && data["donate"] == "N" && type != "A"
|
|
163
|
+
check.required("carrierType", is: 6)
|
|
164
|
+
end
|
|
165
|
+
return if %w[A H].include?(type)
|
|
166
|
+
|
|
167
|
+
check.optional("buyerUn", is: 8)
|
|
168
|
+
check.optional("buyerTitle", max: 60)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def issue_by_type(check, data, type)
|
|
172
|
+
prefix = "#{data['companyUn']}_#{data['orgId']}_"
|
|
173
|
+
print_mode = data["paperPrintMode"].to_s.to_i
|
|
174
|
+
|
|
175
|
+
if %w[I R G H].include?(type)
|
|
176
|
+
check.required("saleIdentifier", max: 100, prefix: prefix)
|
|
177
|
+
end
|
|
178
|
+
if %w[A H].include?(type)
|
|
179
|
+
check.required("allowanceIdentifier", max: 100, prefix: prefix)
|
|
180
|
+
check.required("allowanceExclusiveAmount", max: 20)
|
|
181
|
+
check.required("allowanceTax", max: 8)
|
|
182
|
+
check.required("allowancePaperReturned", in: YES_NO)
|
|
183
|
+
check.required("allowanceInclusiveAmount", max: 20)
|
|
184
|
+
end
|
|
185
|
+
check.required("invoiceNumber", is: 10) if %w[R G H].include?(type)
|
|
186
|
+
if type == "H"
|
|
187
|
+
check.required("allowanceNumber", is: 16, prefix: data["orgId"].to_s)
|
|
188
|
+
check.required("allowanceDate", format: DATE)
|
|
189
|
+
end
|
|
190
|
+
check.optional("allowaDeclaration", format: /\A\d{6}\z/) if type == "A"
|
|
191
|
+
|
|
192
|
+
if %w[I R G].include?(type)
|
|
193
|
+
check.required("transactionTime", format: TIME)
|
|
194
|
+
check.required("total", max: 20)
|
|
195
|
+
check.total_matches_items
|
|
196
|
+
if blank?(data["buyerUn"]) && print_mode.zero?
|
|
197
|
+
check.required("donate", is: 1)
|
|
198
|
+
end
|
|
199
|
+
check.required("donationUnit", max: 10) if data["donate"] == "Y"
|
|
200
|
+
if print_mode.zero? && data["donate"] == "N"
|
|
201
|
+
check.required("carrierId", max: 64)
|
|
202
|
+
check.required("carrierIdHidden", max: 64)
|
|
203
|
+
end
|
|
204
|
+
end
|
|
205
|
+
if %w[I R G A].include?(type)
|
|
206
|
+
check.optional("receiverName", max: 30)
|
|
207
|
+
check.optional("receiverAddrZip", max: 6)
|
|
208
|
+
check.optional("receiverAddrRoad", max: 100)
|
|
209
|
+
check.optional("receiverEmail", max: 80)
|
|
210
|
+
check.optional("receiverMobile", max: 15)
|
|
211
|
+
end
|
|
212
|
+
check.optional("tax", max: 20) if %w[I G].include?(type)
|
|
213
|
+
issue_type_g(check) if type == "G"
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
def issue_type_g(check)
|
|
217
|
+
check.optional("checkNumber", is: 4)
|
|
218
|
+
check.optional("invoiceDate", is: 8)
|
|
219
|
+
check.optional("invoiceTime", is: 8)
|
|
220
|
+
%w[texclusiveAmount oeclusiveAmount zexclusiveAmount].each do |field|
|
|
221
|
+
check.optional(field, max: 20)
|
|
222
|
+
end
|
|
223
|
+
check.optional("mainRemark", max: 300)
|
|
224
|
+
check.optional("invoiceType", in: %w[07 08])
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def issue_items(check, data, type)
|
|
228
|
+
items = data["itemList"]
|
|
229
|
+
unless items.is_a?(Array) && !items.empty?
|
|
230
|
+
check.add("itemList", "is required")
|
|
231
|
+
return
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
items = items.map { |item| stringify(item) }
|
|
235
|
+
items.each_with_index do |item, index|
|
|
236
|
+
item_errors(item).each do |field, messages|
|
|
237
|
+
messages.each { |message| check.add("itemList[#{index}].#{field}", message) }
|
|
238
|
+
end
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
needed = %w[itemTotal taxType]
|
|
242
|
+
needed += %w[invoiceNumber invoiceDate itemExclude] if %w[A H].include?(type)
|
|
243
|
+
needed.each do |field|
|
|
244
|
+
check.add("itemList", "needs #{field} on every item") if items.any? { |i| blank?(i[field]) }
|
|
245
|
+
end
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
def stringify(hash)
|
|
249
|
+
return {} unless hash.is_a?(Hash)
|
|
250
|
+
|
|
251
|
+
hash.to_h { |key, value| [key.to_s, value] }
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
def blank?(value)
|
|
255
|
+
value.nil? || value.to_s.strip.empty?
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
# Collects messages for one Hash. Lengths count characters, as the 1.x
|
|
259
|
+
# validators did.
|
|
260
|
+
class Check
|
|
261
|
+
attr_reader :errors
|
|
262
|
+
|
|
263
|
+
def initialize(data)
|
|
264
|
+
@data = data
|
|
265
|
+
@errors = {}
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def add(field, message)
|
|
269
|
+
(@errors[field] ||= []) << message
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
def unknown_keys(allowed)
|
|
273
|
+
(@data.keys - allowed).each { |key| add(key, "is not a DEFAULTAPI field") }
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
def required(field, **rule)
|
|
277
|
+
return add(field, "is required") if Rules.blank?(@data[field])
|
|
278
|
+
|
|
279
|
+
apply(field, **rule)
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
def optional(field, **rule)
|
|
283
|
+
apply(field, **rule) unless Rules.blank?(@data[field])
|
|
284
|
+
end
|
|
285
|
+
|
|
286
|
+
def total_matches_items
|
|
287
|
+
items = Array(@data["itemList"]).map { |item| Rules.stringify(item) }
|
|
288
|
+
# Only whole decimal strings: String#to_r would read "100oops" as 100.
|
|
289
|
+
values = [@data["total"], *items.map { |item| item["itemTotal"] }].map(&:to_s)
|
|
290
|
+
return add("total", "and every itemTotal must be decimal numbers") unless values.all?(DECIMAL)
|
|
291
|
+
|
|
292
|
+
# Compared as decimals: "0.5" + "0.5" is "1".
|
|
293
|
+
sum = items.sum { |item| item["itemTotal"].to_s.to_r }
|
|
294
|
+
return if @data["total"].to_s.to_r == sum
|
|
295
|
+
|
|
296
|
+
add("total", "must equal the sum of itemTotal (#{Number.plain(sum)})")
|
|
297
|
+
end
|
|
298
|
+
|
|
299
|
+
private
|
|
300
|
+
|
|
301
|
+
def apply(field, is: nil, max: nil, in: nil, format: nil, prefix: nil)
|
|
302
|
+
value = @data[field].to_s
|
|
303
|
+
choices = binding.local_variable_get(:in)
|
|
304
|
+
add(field, "must be #{is} characters") if is && value.length != is
|
|
305
|
+
add(field, "must be #{max} characters or fewer") if max && value.length > max
|
|
306
|
+
add(field, "must be one of #{choices.join(', ')}") if choices && !choices.include?(value)
|
|
307
|
+
add(field, "has an invalid format") if format && !value.match?(format)
|
|
308
|
+
add(field, "must start with #{prefix}") if prefix && !value.start_with?(prefix)
|
|
309
|
+
end
|
|
310
|
+
end
|
|
311
|
+
end
|
|
312
|
+
end
|
|
313
|
+
end
|
|
314
|
+
end
|