einvoice 1.5.0 → 2.0.0.beta1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/.coderabbit.yaml +6 -8
- data/.github/workflows/build.yml +6 -3
- data/.github/workflows/cron.yml +4 -2
- data/CHANGELOG.md +63 -44
- data/Gemfile +3 -10
- data/README.md +284 -325
- data/README.zh-TW.md +381 -0
- data/Rakefile +2 -51
- data/bin/console +3 -6
- data/einvoice.gemspec +17 -18
- data/lib/einvoice/amego/client.rb +116 -0
- data/lib/einvoice/amego/errors.rb +84 -0
- data/lib/einvoice/amego/payload.rb +270 -0
- data/lib/einvoice/amego/provider.rb +272 -0
- data/lib/einvoice/amego.rb +27 -0
- data/lib/einvoice/capability.rb +79 -0
- data/lib/einvoice/ecpay/client.rb +184 -0
- data/lib/einvoice/ecpay/crypto.rb +85 -0
- data/lib/einvoice/ecpay/errors.rb +115 -0
- data/lib/einvoice/ecpay/payload.rb +241 -0
- data/lib/einvoice/ecpay/provider.rb +371 -0
- data/lib/einvoice/ecpay.rb +31 -0
- data/lib/einvoice/error.rb +220 -0
- data/lib/einvoice/ezpay/client.rb +130 -0
- data/lib/einvoice/ezpay/crypto.rb +85 -0
- data/lib/einvoice/ezpay/errors.rb +72 -0
- data/lib/einvoice/ezpay/payload.rb +269 -0
- data/lib/einvoice/ezpay/provider.rb +253 -0
- data/lib/einvoice/ezpay.rb +19 -0
- data/lib/einvoice/input.rb +547 -0
- data/lib/einvoice/mock_provider.rb +191 -0
- data/lib/einvoice/mof/donation_codes.rb +157 -0
- data/lib/einvoice/mof.rb +16 -0
- data/lib/einvoice/number.rb +91 -0
- data/lib/einvoice/provider.rb +57 -13
- data/lib/einvoice/redaction.rb +54 -0
- data/lib/einvoice/taipei.rb +89 -0
- data/lib/einvoice/tax_split.rb +112 -0
- data/lib/einvoice/tradevan/default_api/client.rb +175 -0
- data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
- data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
- data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
- data/lib/einvoice/tradevan/default_api/provider.rb +353 -0
- data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
- data/lib/einvoice/tradevan.rb +25 -0
- data/lib/einvoice/types.rb +365 -0
- data/lib/einvoice/version.rb +3 -1
- data/lib/einvoice.rb +21 -9
- metadata +52 -144
- data/docs/Tradevan E-Invoice APIs.md +0 -201
- data/docs/neweb.md +0 -347
- data/lib/einvoice/client.rb +0 -21
- data/lib/einvoice/configuration.rb +0 -49
- data/lib/einvoice/connection.rb +0 -31
- data/lib/einvoice/donation_unit_list.json +0 -2025
- data/lib/einvoice/result.rb +0 -21
- data/lib/einvoice/tradevan/model/base.rb +0 -34
- data/lib/einvoice/tradevan/model/issue_data.rb +0 -129
- data/lib/einvoice/tradevan/model/issue_item.rb +0 -41
- data/lib/einvoice/tradevan/model/void_data.rb +0 -35
- data/lib/einvoice/tradevan/provider.rb +0 -139
- data/lib/einvoice/tradevan/result.rb +0 -25
- data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
- data/lib/faraday/response/decode_tradevan.rb +0 -37
- data/lib/faraday/response/parse_xml.rb +0 -14
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module Tradevan
|
|
5
|
+
module DefaultAPI
|
|
6
|
+
# Builds +issueData+ and +voidData+ from the unified inputs.
|
|
7
|
+
#
|
|
8
|
+
# Nobody has run these against the live API in 2026, so each choice that
|
|
9
|
+
# the sources do not settle is named in a comment, and
|
|
10
|
+
# docs/providers/tradevan/defaultapi.md lists the open questions.
|
|
11
|
+
module Payload
|
|
12
|
+
TAX_TYPE = {
|
|
13
|
+
TaxType::TAXABLE => "T",
|
|
14
|
+
TaxType::ZERO_RATED => "Z",
|
|
15
|
+
TaxType::TAX_FREE => "O"
|
|
16
|
+
}.freeze
|
|
17
|
+
|
|
18
|
+
CARRIER_TYPE = {
|
|
19
|
+
CarrierType::MOBILE_BARCODE => "3J0002",
|
|
20
|
+
CarrierType::CITIZEN_CERTIFICATE => "CQ0001"
|
|
21
|
+
}.freeze
|
|
22
|
+
|
|
23
|
+
# The only taxable rate: DEFAULTAPI has no rate field.
|
|
24
|
+
TAX_RATE = Rational(5, 100)
|
|
25
|
+
|
|
26
|
+
module_function
|
|
27
|
+
|
|
28
|
+
# +issueData+ for type +I+ (a new invoice). +now+ is the time of this
|
|
29
|
+
# issue: Tradevan requires +transactionDate+ and +transactionTime+.
|
|
30
|
+
def issue(parsed, settings, now)
|
|
31
|
+
types = parsed.item_tax_types
|
|
32
|
+
check_tax!(types, parsed.tax_rate)
|
|
33
|
+
breakdown = parsed.tax_breakdown
|
|
34
|
+
check_total!(breakdown)
|
|
35
|
+
sale = sale_identifier(settings, parsed.order_id)
|
|
36
|
+
|
|
37
|
+
data = header(settings).merge(
|
|
38
|
+
"type" => "I",
|
|
39
|
+
"saleIdentifier" => sale,
|
|
40
|
+
"transactionNumber" => parsed.order_id.to_s,
|
|
41
|
+
"transactionDate" => now.strftime("%Y%m%d"),
|
|
42
|
+
"transactionTime" => now.strftime("%H:%M:%S"),
|
|
43
|
+
"total" => number(breakdown.total_amount),
|
|
44
|
+
"invoicePaperReturned" => settings.invoice_paper_returned,
|
|
45
|
+
"itemList" => items(parsed.items, breakdown.lines, sale)
|
|
46
|
+
)
|
|
47
|
+
data.merge!(buyer(parsed))
|
|
48
|
+
data.merge!(donation_and_carrier(parsed, settings))
|
|
49
|
+
data.compact
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# +voidData+ for type +I+ (void an invoice). +sale+ is the original
|
|
53
|
+
# invoice's +saleIdentifier+ (docs, section 4.1).
|
|
54
|
+
def void(parsed, settings, sale)
|
|
55
|
+
{
|
|
56
|
+
"type" => "I",
|
|
57
|
+
"saleIdentifier" => sale,
|
|
58
|
+
"invoiceNumber" => parsed.invoice.number.to_s,
|
|
59
|
+
"invoicePaperReturned" => settings.invoice_paper_returned
|
|
60
|
+
}
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# +issueData+ for type +A+ (a new allowance). +sale+ and +invoice_date+
|
|
64
|
+
# are the original invoice's (docs, section 4.1). +today+ is a Date.
|
|
65
|
+
def allowance(parsed, settings, sale:, invoice_date:, today:)
|
|
66
|
+
breakdown = parsed.tax_breakdown
|
|
67
|
+
check_tax!(breakdown.lines.map(&:tax_type), parsed.tax_rate)
|
|
68
|
+
amount = parsed.amount
|
|
69
|
+
header(settings).merge(
|
|
70
|
+
"type" => "A",
|
|
71
|
+
"allowanceIdentifier" => sale_identifier(settings, parsed.allowance_id),
|
|
72
|
+
"transactionNumber" => parsed.allowance_id.to_s,
|
|
73
|
+
"transactionDate" => today.strftime("%Y%m%d"),
|
|
74
|
+
"allowanceExclusiveAmount" => number(amount.sales_amount),
|
|
75
|
+
"allowanceTax" => number(amount.tax_amount),
|
|
76
|
+
"allowanceInclusiveAmount" => number(amount.total_amount),
|
|
77
|
+
"allowancePaperReturned" => settings.allowance_paper_returned,
|
|
78
|
+
"invoicePaperReturned" => settings.invoice_paper_returned,
|
|
79
|
+
"itemList" => allowance_items(parsed, breakdown.lines, sale, invoice_date.strftime("%Y%m%d"))
|
|
80
|
+
)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# +voidData+ for type +A+ (void an allowance).
|
|
84
|
+
def void_allowance(parsed, settings)
|
|
85
|
+
{
|
|
86
|
+
"type" => "A",
|
|
87
|
+
"companyUn" => settings.company_un,
|
|
88
|
+
"allowanceNumber" => parsed.allowance.allowance_number.to_s,
|
|
89
|
+
"allowancePaperReturned" => settings.allowance_paper_returned
|
|
90
|
+
}
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# +"#{companyUn}_#{orgId}_#{id}"+. The prefix is a DEFAULTAPI rule. Using
|
|
94
|
+
# the order id for the rest is our choice, so that a void can rebuild it.
|
|
95
|
+
def sale_identifier(settings, id)
|
|
96
|
+
"#{settings.company_un}_#{settings.org_id}_#{id}"
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# The order id back from a +saleIdentifier+ built by {sale_identifier}.
|
|
100
|
+
# The rest after the prefix. That is the order id for an invoice that
|
|
101
|
+
# this adapter issued. Every saleIdentifier has the prefix [rules], so
|
|
102
|
+
# for another invoice the rest is only a guess. nil without the prefix:
|
|
103
|
+
# building it again from the whole value would double the prefix.
|
|
104
|
+
def order_id_from(settings, sale_identifier)
|
|
105
|
+
prefix = sale_identifier(settings, "")
|
|
106
|
+
value = sale_identifier.to_s
|
|
107
|
+
value.start_with?(prefix) ? value.delete_prefix(prefix) : nil
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def header(settings)
|
|
111
|
+
{
|
|
112
|
+
"companyUn" => settings.company_un,
|
|
113
|
+
"orgId" => settings.org_id,
|
|
114
|
+
"paperPrintMode" => settings.paper_print_mode,
|
|
115
|
+
"invoiceAlarmMode" => settings.invoice_alarm_mode
|
|
116
|
+
}
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
# For types I, R and G, +total+ must equal the sum of +itemTotal+
|
|
120
|
+
# [rules], and +total+ is whole TWD. A type A allowance has no +total+
|
|
121
|
+
# and no such rule, so this check is for an issue only. With amounts
|
|
122
|
+
# that are not whole, the line totals with tax can add up to a
|
|
123
|
+
# fraction, for example 100.5 + 5 = 105.5 against a total of 106.
|
|
124
|
+
# DEFAULTAPI has no field to carry that gap, so such an invoice cannot be
|
|
125
|
+
# sent.
|
|
126
|
+
def check_total!(breakdown)
|
|
127
|
+
# The sum of the values that go out, so the check and the wire agree.
|
|
128
|
+
sum = breakdown.lines.sum { |line| number(line.gross_amount).to_r }
|
|
129
|
+
return if sum == breakdown.total_amount
|
|
130
|
+
|
|
131
|
+
raise UnsupportedError.new("Tradevan DEFAULTAPI needs the item totals with tax " \
|
|
132
|
+
"(#{number(sum)}) to equal the whole-TWD total " \
|
|
133
|
+
"(#{breakdown.total_amount})", provider: Client::PROVIDER)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# DEFAULTAPI has no code for a special tax rate (6.1) and no rate
|
|
137
|
+
# field, so a taxable line has to be at the general rate.
|
|
138
|
+
def check_tax!(types, rate)
|
|
139
|
+
if types.include?(TaxType::SPECIAL)
|
|
140
|
+
raise UnsupportedError.new("Tradevan DEFAULTAPI has no special tax rate (特種稅率)",
|
|
141
|
+
provider: Client::PROVIDER)
|
|
142
|
+
end
|
|
143
|
+
return unless types.include?(TaxType::TAXABLE) && rate.to_r != TAX_RATE
|
|
144
|
+
|
|
145
|
+
raise UnsupportedError.new("Tradevan DEFAULTAPI takes a taxable rate of 0.05 only, got #{rate.to_f}",
|
|
146
|
+
provider: Client::PROVIDER)
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def buyer(parsed)
|
|
150
|
+
buyer = parsed.buyer
|
|
151
|
+
return {} unless buyer
|
|
152
|
+
|
|
153
|
+
# receiverName takes 30 characters, buyerTitle 60. A longer B2B name
|
|
154
|
+
# is cut for receiverName only.
|
|
155
|
+
fields = {
|
|
156
|
+
"receiverName" => buyer.name && buyer.name[0, 30],
|
|
157
|
+
"receiverAddrRoad" => buyer.address,
|
|
158
|
+
"receiverEmail" => buyer.email,
|
|
159
|
+
"receiverMobile" => buyer.phone
|
|
160
|
+
}
|
|
161
|
+
if parsed.resolved_category == InvoiceCategory::B2B
|
|
162
|
+
fields["buyerUn"] = buyer.ubn
|
|
163
|
+
fields["buyerTitle"] = buyer.name
|
|
164
|
+
end
|
|
165
|
+
fields.reject { |_, value| value.to_s.empty? }
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
# A carrier goes with a donation too: the schema allows both (5.1).
|
|
169
|
+
def donation_and_carrier(parsed, settings)
|
|
170
|
+
carrier = parsed.carrier
|
|
171
|
+
if parsed.donation
|
|
172
|
+
fields = { "donate" => "Y", "donationUnit" => parsed.donation.npoban }
|
|
173
|
+
else
|
|
174
|
+
# With donate "N", the 1.x rules ask for a carrier. A B2B invoice
|
|
175
|
+
# without a carrier therefore leaves donate out.
|
|
176
|
+
return {} if carrier.nil? && parsed.resolved_category == InvoiceCategory::B2B
|
|
177
|
+
|
|
178
|
+
fields = { "donate" => "N" }
|
|
179
|
+
end
|
|
180
|
+
return fields unless carrier
|
|
181
|
+
|
|
182
|
+
code = carrier_code(parsed)
|
|
183
|
+
fields.merge("carrierType" => carrier_type(carrier, settings),
|
|
184
|
+
"carrierId" => code, "carrierIdHidden" => code)
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def carrier_type(carrier, settings)
|
|
188
|
+
return CARRIER_TYPE.fetch(carrier.type) unless carrier.type == CarrierType::MEMBER
|
|
189
|
+
return settings.member_carrier_type unless settings.member_carrier_type.to_s.empty?
|
|
190
|
+
|
|
191
|
+
raise ValidationError.new("A member carrier needs member_carrier_type, the merchant's " \
|
|
192
|
+
"own 6-character code from Tradevan", provider: Client::PROVIDER)
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# A member carrier without a code uses the buyer's email, then phone.
|
|
196
|
+
# This is our choice: the sources do not say what Tradevan expects.
|
|
197
|
+
def carrier_code(parsed)
|
|
198
|
+
code = parsed.carrier.code.to_s
|
|
199
|
+
return code unless code.empty?
|
|
200
|
+
|
|
201
|
+
fallback = [parsed.buyer&.email, parsed.buyer&.phone].map(&:to_s).find { |v| !v.empty? }
|
|
202
|
+
return fallback if fallback && parsed.carrier.type == CarrierType::MEMBER
|
|
203
|
+
|
|
204
|
+
raise ValidationError.new("The carrier needs a code", provider: Client::PROVIDER)
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# +itemTotal+ is tax included (4.3), so every price mode is sent as the
|
|
208
|
+
# core's gross line amount and unit price.
|
|
209
|
+
def items(list, lines, sale)
|
|
210
|
+
list.zip(lines).each_with_index.map do |(item, line), index|
|
|
211
|
+
{
|
|
212
|
+
"saleIdentifier" => sale,
|
|
213
|
+
"serialNumber" => format("%04d", index + 1),
|
|
214
|
+
"productName" => item.description.to_s,
|
|
215
|
+
"qty" => number(item.quantity),
|
|
216
|
+
"price" => number(line.gross_unit_price),
|
|
217
|
+
"itemTotal" => number(line.gross_amount),
|
|
218
|
+
"taxType" => TAX_TYPE.fetch(line.tax_type)
|
|
219
|
+
}
|
|
220
|
+
end
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
# Each allowance line carries its tax split (G0401): +itemExclude+
|
|
224
|
+
# without tax, +tax+, and +itemTotal+ with tax, all from the core.
|
|
225
|
+
def allowance_items(parsed, lines, sale, invoice_date)
|
|
226
|
+
parsed.items.zip(lines).each_with_index.map do |(item, line), index|
|
|
227
|
+
{
|
|
228
|
+
"saleIdentifier" => sale,
|
|
229
|
+
"serialNumber" => format("%04d", index + 1),
|
|
230
|
+
"invoiceNumber" => parsed.invoice.number.to_s,
|
|
231
|
+
"invoiceDate" => invoice_date,
|
|
232
|
+
"productName" => item.description.to_s,
|
|
233
|
+
"qty" => number(item.quantity),
|
|
234
|
+
"price" => number(line.gross_unit_price),
|
|
235
|
+
"itemExclude" => number(line.net_amount),
|
|
236
|
+
"tax" => number(line.tax),
|
|
237
|
+
"itemTotal" => number(line.gross_amount),
|
|
238
|
+
"taxType" => TAX_TYPE.fetch(line.tax_type)
|
|
239
|
+
}
|
|
240
|
+
end
|
|
241
|
+
end
|
|
242
|
+
|
|
243
|
+
# DEFAULTAPI sends every value as a string. Whole numbers lose their ".0".
|
|
244
|
+
# Other numbers are written in fixed
|
|
245
|
+
# point with up to 7 decimal places (MIG 表 15-5), never as "1.0e-07".
|
|
246
|
+
# A Float is read through its shortest form, so 0.1 stays 0.1 and not
|
|
247
|
+
# its binary approximation.
|
|
248
|
+
def number(value)
|
|
249
|
+
return value if value.is_a?(String)
|
|
250
|
+
|
|
251
|
+
rational = (value.is_a?(Float) ? value.to_s.to_r : value.to_r).round(7)
|
|
252
|
+
return rational.to_i.to_s if rational.denominator == 1
|
|
253
|
+
|
|
254
|
+
format("%.7f", rational).sub(/0+\z/, "")
|
|
255
|
+
end
|
|
256
|
+
end
|
|
257
|
+
end
|
|
258
|
+
end
|
|
259
|
+
end
|
|
@@ -0,0 +1,353 @@
|
|
|
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 = parsed.resolved_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 parsed.resolved_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. A missing number is nil, not 0.
|
|
309
|
+
# A value that is not a decimal number, such as "unavailable" or
|
|
310
|
+
# "5abc", is an error: String#to_r would read it as 0 or 5, a number
|
|
311
|
+
# that Tradevan did not send.
|
|
312
|
+
def numeric(row, field)
|
|
313
|
+
Number.response_plain(row[field], field: "detailList #{field}", provider: name, raw: row)
|
|
314
|
+
end
|
|
315
|
+
|
|
316
|
+
# A header total as an Integer. A missing total is 0: no live response
|
|
317
|
+
# shows if Tradevan can leave one out (4.3). A total with decimals is an
|
|
318
|
+
# error, not cut off.
|
|
319
|
+
def total(result, field)
|
|
320
|
+
Number.response_integer!(result[field], field: field, provider: name, raw: result, if_missing: 0)
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
def string_keys(hash)
|
|
324
|
+
return {} unless hash.is_a?(Hash)
|
|
325
|
+
|
|
326
|
+
hash.to_h { |key, value| [key.to_s, value] }
|
|
327
|
+
end
|
|
328
|
+
|
|
329
|
+
def presence(value)
|
|
330
|
+
string = value.to_s
|
|
331
|
+
string.empty? ? nil : string
|
|
332
|
+
end
|
|
333
|
+
|
|
334
|
+
# "20160425" and "12:34:58" (UTC+8) → Time, or nil when the date is
|
|
335
|
+
# missing, so that a missing date never reads as "now". A date or a
|
|
336
|
+
# time that is there but not valid is the provider's error.
|
|
337
|
+
def parse_time(date, time)
|
|
338
|
+
return nil if date.to_s.empty?
|
|
339
|
+
|
|
340
|
+
year, month, day = /\A(\d{4})(\d{2})(\d{2})\z/.match(date.to_s)&.captures&.map(&:to_i)
|
|
341
|
+
clock = time.to_s.empty? ? "00:00:00" : time.to_s
|
|
342
|
+
hour, minute, second = /\A(\d{2}):(\d{2}):(\d{2})\z/.match(clock)&.captures&.map(&:to_i)
|
|
343
|
+
unless year && hour && Date.valid_date?(year, month, day) && hour < 24 && minute < 60 && second < 60
|
|
344
|
+
raise ProviderError.new("Tradevan returned a date that is not valid: #{date.inspect} #{time.inspect}",
|
|
345
|
+
provider: name)
|
|
346
|
+
end
|
|
347
|
+
|
|
348
|
+
Time.new(year, month, day, hour, minute, second, "+08:00")
|
|
349
|
+
end
|
|
350
|
+
end
|
|
351
|
+
end
|
|
352
|
+
end
|
|
353
|
+
end
|