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,175 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
|
|
7
|
+
module Einvoice
|
|
8
|
+
module Tradevan
|
|
9
|
+
module DefaultAPI
|
|
10
|
+
# Speaks the DEFAULTAPI wire protocol: encrypt the parameters into +v+,
|
|
11
|
+
# send it in the query string (also for the POST endpoints, as the 1.x
|
|
12
|
+
# client did), then read the +Success+ / +Message+ envelope and raise the
|
|
13
|
+
# matching {Einvoice::Error} subclass.
|
|
14
|
+
#
|
|
15
|
+
# Callers get the decrypted +Message+ back and never see the envelope.
|
|
16
|
+
class Client
|
|
17
|
+
PROVIDER = "tradevan"
|
|
18
|
+
PATH_PREFIX = "/DEFAULTAPI/"
|
|
19
|
+
# The envelope's +Success+ values. A body with another value was not
|
|
20
|
+
# written by DEFAULTAPI, so the HTTP status decides.
|
|
21
|
+
SUCCESS_VALUES = %w[Y N E].freeze
|
|
22
|
+
|
|
23
|
+
attr_reader :base_url, :timeout
|
|
24
|
+
|
|
25
|
+
# @param base_url [String] the Tradevan host. There is no default: the
|
|
26
|
+
# 1.x client never shipped one, and the hosts are not public.
|
|
27
|
+
def initialize(acnt:, acntp:, key1:, key2:, base_url:, timeout: 30)
|
|
28
|
+
if base_url.to_s.empty?
|
|
29
|
+
raise ValidationError.new("Tradevan base_url is required", provider: PROVIDER)
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
@acnt = acnt.to_s
|
|
33
|
+
@acntp = acntp.to_s
|
|
34
|
+
@key1 = key1.to_s
|
|
35
|
+
@key2 = key2.to_s
|
|
36
|
+
# Frozen: the checks above must hold for every request after this.
|
|
37
|
+
@base_url = Redaction.base_url!(base_url, provider: PROVIDER)
|
|
38
|
+
@timeout = timeout
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def inspect
|
|
42
|
+
"#<#{self.class.name} base_url=#{@base_url.inspect} acnt=#{@acnt.inspect} " \
|
|
43
|
+
"acntp=#{Redaction::FILTERED} key1=#{Redaction::FILTERED} key2=#{Redaction::FILTERED}>"
|
|
44
|
+
end
|
|
45
|
+
alias to_s inspect
|
|
46
|
+
|
|
47
|
+
# Call +path+ (for example +"post/issue"+ or +"get/searchInvoiceDetail"+)
|
|
48
|
+
# with +params+, and return the decrypted +Message+. A path that starts
|
|
49
|
+
# with +post/+ is sent as POST, everything else as GET.
|
|
50
|
+
def request(path, params)
|
|
51
|
+
v = Crypto.encode_params(params, acnt: @acnt, acntp: @acntp, key1: @key1, key2: @key2)
|
|
52
|
+
read(*send_request(path, v))
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Raise unless the inner status field (+issueStatus+, +voidStatus+) is
|
|
56
|
+
# +"Y"+. +Success: "Y"+ alone only means the envelope was read.
|
|
57
|
+
def check_status!(result, field)
|
|
58
|
+
return if result.is_a?(Hash) && result[field] == "Y"
|
|
59
|
+
|
|
60
|
+
reason = result.is_a?(Hash) ? result["failReason"].to_s : ""
|
|
61
|
+
raise_business(reason, result)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
private
|
|
65
|
+
|
|
66
|
+
def send_request(path, v)
|
|
67
|
+
uri = URI("#{@base_url}#{PATH_PREFIX}#{path}")
|
|
68
|
+
uri.query = URI.encode_www_form(v: v)
|
|
69
|
+
|
|
70
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
71
|
+
http.use_ssl = uri.scheme == "https"
|
|
72
|
+
http.open_timeout = @timeout
|
|
73
|
+
http.read_timeout = @timeout
|
|
74
|
+
response = nil
|
|
75
|
+
http.request(build_request(path, uri)) { |res| (response = res).read_body }
|
|
76
|
+
[parse(response), response]
|
|
77
|
+
rescue *Error::NETWORK_ERRORS => e
|
|
78
|
+
raise NetworkError.for_failure(e, provider: PROVIDER, name: "Tradevan", response: response)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def build_request(path, uri)
|
|
82
|
+
request = if path.start_with?("post/")
|
|
83
|
+
Net::HTTP::Post.new(uri.request_uri).tap do |post|
|
|
84
|
+
post["Content-Type"] = "application/x-www-form-urlencoded"
|
|
85
|
+
post.body = ""
|
|
86
|
+
end
|
|
87
|
+
else
|
|
88
|
+
Net::HTTP::Get.new(uri.request_uri)
|
|
89
|
+
end
|
|
90
|
+
request["Accept"] = "application/json; charset=utf-8"
|
|
91
|
+
request
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
# A body that Tradevan wrote (a JSON object with +Success+) decides the
|
|
95
|
+
# error, whatever the HTTP status. Any other body falls back to the
|
|
96
|
+
# status: HTTP 429 and 5xx are a NetworkError, so the caller can retry
|
|
97
|
+
# (docs/providers/README.md, "The unified model").
|
|
98
|
+
def parse(response)
|
|
99
|
+
body = JSON.parse(response.body.to_s)
|
|
100
|
+
return body if body.is_a?(Hash) && SUCCESS_VALUES.include?(body["Success"])
|
|
101
|
+
|
|
102
|
+
raise_for_status!(response)
|
|
103
|
+
body
|
|
104
|
+
rescue JSON::ParserError => e
|
|
105
|
+
raise_for_status!(response)
|
|
106
|
+
raise ProviderError.new("Tradevan returned a non-JSON response (HTTP #{response.code})",
|
|
107
|
+
provider: PROVIDER, raw_code: response.code, cause: e)
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def raise_for_status!(response)
|
|
111
|
+
error = NetworkError.for_status(response, provider: PROVIDER)
|
|
112
|
+
raise error if error
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def read(envelope, response)
|
|
116
|
+
unless envelope.is_a?(Hash)
|
|
117
|
+
raise ProviderError.new("Tradevan returned an unexpected envelope", provider: PROVIDER,
|
|
118
|
+
raw: envelope)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
case envelope["Success"]
|
|
122
|
+
when "Y" then message(envelope, response)
|
|
123
|
+
when "N" then raise_failure(envelope, response)
|
|
124
|
+
when "E" then raise_transport(envelope, response)
|
|
125
|
+
else
|
|
126
|
+
raise ProviderError.new("Tradevan returned an unknown Success value: " \
|
|
127
|
+
"#{envelope['Success'].inspect}", provider: PROVIDER, raw: envelope)
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# +Success: "N"+ carries an encrypted Message, like a success does.
|
|
132
|
+
# The decrypted +Message+. When it cannot be read, the envelope tells
|
|
133
|
+
# nothing, so HTTP 429 and 5xx decide, as for any other body.
|
|
134
|
+
def message(envelope, response)
|
|
135
|
+
Crypto.decrypt_message(envelope["Message"], @key1)
|
|
136
|
+
rescue ProviderError
|
|
137
|
+
raise_for_status!(response)
|
|
138
|
+
raise
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def raise_failure(envelope, response)
|
|
142
|
+
result = message(envelope, response)
|
|
143
|
+
reason = result.is_a?(Hash) ? result["failReason"].to_s : ""
|
|
144
|
+
raise_business(reason, result)
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# +Success: "E"+ carries a plain text Message. Without readable text,
|
|
148
|
+
# the envelope tells nothing, so HTTP 429 and 5xx decide. Otherwise it
|
|
149
|
+
# is a plain ProviderError: an object such as {"password" => nil} must
|
|
150
|
+
# not reach the patterns, which would read it as a credential error.
|
|
151
|
+
def raise_transport(envelope, response)
|
|
152
|
+
message = envelope["Message"]
|
|
153
|
+
unless message.is_a?(String) && !message.strip.empty?
|
|
154
|
+
raise_for_status!(response)
|
|
155
|
+
raise ProviderError.new("Tradevan returned an error without a readable message",
|
|
156
|
+
provider: PROVIDER, raw_code: "E", raw: envelope)
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
code, reason = Errors.classify_transport(message)
|
|
160
|
+
raise Einvoice::Error.for(
|
|
161
|
+
code, message, provider: PROVIDER, reason: reason, raw_code: "E", raw_message: message, raw: envelope
|
|
162
|
+
)
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
def raise_business(message, raw)
|
|
166
|
+
code, reason = Errors.classify(message)
|
|
167
|
+
raise Einvoice::Error.for(
|
|
168
|
+
code, message.empty? ? "Tradevan returned an error" : message,
|
|
169
|
+
provider: PROVIDER, reason: reason, raw_code: "N", raw_message: message, raw: raw
|
|
170
|
+
)
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
end
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "json"
|
|
5
|
+
|
|
6
|
+
module Einvoice
|
|
7
|
+
module Tradevan
|
|
8
|
+
module DefaultAPI
|
|
9
|
+
# The DEFAULTAPI cipher, ported from the 1.x client (which ran in
|
|
10
|
+
# production for years): AES-128-CBC with the key reused as the IV, no
|
|
11
|
+
# PKCS padding, the plain text padded with NUL bytes, and strict Base64.
|
|
12
|
+
#
|
|
13
|
+
# A request carries one parameter, +v+. Each API parameter is encrypted
|
|
14
|
+
# with +key1+, the result is wrapped with the plain +acnt+ / +acntp+ in a
|
|
15
|
+
# JSON object, and that object is encrypted with +key2+. A response
|
|
16
|
+
# +Message+ is decrypted with +key1+: the 1.x code did so, and Tradevan's
|
|
17
|
+
# own document (which says +key2+) was wrong on this point.
|
|
18
|
+
module Crypto
|
|
19
|
+
BLOCK = 16
|
|
20
|
+
|
|
21
|
+
module_function
|
|
22
|
+
|
|
23
|
+
# Encrypt +plaintext+ with +key+ and return strict Base64.
|
|
24
|
+
def encrypt(plaintext, key)
|
|
25
|
+
cipher = new_cipher(key, :encrypt)
|
|
26
|
+
[cipher.update(pad(plaintext.to_s.b)) + cipher.final].pack("m0")
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Reverse of {encrypt}. Trailing NUL padding is removed.
|
|
30
|
+
def decrypt(base64, key)
|
|
31
|
+
cipher = new_cipher(key, :decrypt)
|
|
32
|
+
plain = cipher.update(base64.to_s.unpack1("m")) + cipher.final
|
|
33
|
+
plain.sub(/\0+\z/, "").force_encoding(Encoding::UTF_8)
|
|
34
|
+
rescue OpenSSL::Cipher::CipherError, ArgumentError => e
|
|
35
|
+
raise ProviderError.new("Could not decrypt the Tradevan response",
|
|
36
|
+
provider: Client::PROVIDER, cause: e)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# Build the +v+ query value for one call. A Hash parameter is sent as
|
|
40
|
+
# JSON; anything else as its string form.
|
|
41
|
+
def encode_params(params, acnt:, acntp:, key1:, key2:)
|
|
42
|
+
encrypted = params.to_h { |name, value| [name.to_s, encrypt(serialize(value), key1)] }
|
|
43
|
+
envelope = { "acnt" => acnt.to_s, "acntp" => acntp.to_s }.merge(encrypted)
|
|
44
|
+
encrypt(JSON.generate(envelope), key2)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Read an encrypted response +Message+ back into a Hash or an Array. Some
|
|
48
|
+
# raw endpoints answer an Array. Anything else, such as +null+, is not a
|
|
49
|
+
# message the adapter can read.
|
|
50
|
+
def decrypt_message(message, key1)
|
|
51
|
+
result = JSON.parse(decrypt(message, key1))
|
|
52
|
+
return result if result.is_a?(Hash) || result.is_a?(Array)
|
|
53
|
+
|
|
54
|
+
raise ProviderError.new("Tradevan returned a message that is not a JSON object or array",
|
|
55
|
+
provider: Client::PROVIDER, raw: result)
|
|
56
|
+
rescue JSON::ParserError => e
|
|
57
|
+
raise ProviderError.new("Tradevan returned a malformed JSON message",
|
|
58
|
+
provider: Client::PROVIDER, cause: e)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# Pad with NUL bytes to a whole block. An empty text becomes one block of
|
|
62
|
+
# NULs; a text that already fills whole blocks gets nothing.
|
|
63
|
+
def pad(bytes)
|
|
64
|
+
remainder = bytes.bytesize % BLOCK
|
|
65
|
+
return bytes if remainder.zero? && !bytes.empty?
|
|
66
|
+
|
|
67
|
+
bytes + ("\0" * (BLOCK - remainder))
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def serialize(value)
|
|
71
|
+
value.is_a?(Hash) ? JSON.generate(value) : value.to_s
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def new_cipher(key, direction)
|
|
75
|
+
size = key.to_s.bytesize
|
|
76
|
+
unless size == BLOCK
|
|
77
|
+
raise ValidationError.new("Tradevan keys must be 16 bytes (AES-128-CBC), got #{size}",
|
|
78
|
+
provider: Client::PROVIDER)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
cipher = OpenSSL::Cipher.new("aes-128-cbc").public_send(direction)
|
|
82
|
+
cipher.padding = 0
|
|
83
|
+
cipher.key = key
|
|
84
|
+
cipher.iv = key
|
|
85
|
+
cipher
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module Tradevan
|
|
5
|
+
module DefaultAPI
|
|
6
|
+
# Maps DEFAULTAPI failures onto the unified {Einvoice::Error} tree.
|
|
7
|
+
#
|
|
8
|
+
# DEFAULTAPI has no error code list. A failure is +Success: "E"+ with a
|
|
9
|
+
# plain text +Message+, or +Success: "N"+ (or an inner +issueStatus+ /
|
|
10
|
+
# +voidStatus+ of +"N"+) with a free text +failReason+. The only failure
|
|
11
|
+
# text on record is +duplicated+, and it comes from a 1.x spec stub, not
|
|
12
|
+
# from a real response. So every pattern below is a guess, kept in one
|
|
13
|
+
# place so that real texts can replace it.
|
|
14
|
+
#
|
|
15
|
+
# Unknown failures fall back to +:provider+, not +:validation+: with so few
|
|
16
|
+
# samples, an unknown failure is more likely a provider problem than bad
|
|
17
|
+
# input.
|
|
18
|
+
module Errors
|
|
19
|
+
# Whole English words only: "keyword" is not about a key.
|
|
20
|
+
CREDENTIALS = /帳號|密碼|金鑰|\b(acntp?|keys?|key[12]|password|account)\b/i
|
|
21
|
+
DUPLICATE = /duplicat|重[複覆]/i
|
|
22
|
+
# Checked before ALREADY_VOID: "已作廢,不能折讓" is a refusal, and the
|
|
23
|
+
# refusal is the part the caller can act on. 不能 must come after 作廢
|
|
24
|
+
# and before 折讓, so "發票不能作廢,因為已折讓" (a blocked void) falls
|
|
25
|
+
# through to ALLOWANCE_MADE.
|
|
26
|
+
BLOCKED_BY_VOID = /作廢.*不能.*折讓/
|
|
27
|
+
ALREADY_VOID = /已(被)?作廢/
|
|
28
|
+
ALLOWANCE_MADE = /已折讓|折讓過/
|
|
29
|
+
MISSING = /查無|不存在|not\s*found/i
|
|
30
|
+
|
|
31
|
+
module_function
|
|
32
|
+
|
|
33
|
+
# +Success: "E"+: the request did not reach the business logic.
|
|
34
|
+
def classify_transport(message)
|
|
35
|
+
return [:auth, Reason::CREDENTIALS_INVALID] if message.to_s.match?(CREDENTIALS)
|
|
36
|
+
|
|
37
|
+
[:provider, nil]
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# +Success: "N"+, or an inner status of +"N"+.
|
|
41
|
+
def classify(message)
|
|
42
|
+
case message.to_s
|
|
43
|
+
when DUPLICATE then [:conflict, Reason::DUPLICATE_ORDER]
|
|
44
|
+
when BLOCKED_BY_VOID then [:conflict, Reason::ALLOWANCE_BLOCKED_BY_VOID]
|
|
45
|
+
when ALREADY_VOID then [:conflict, Reason::ALREADY_VOIDED]
|
|
46
|
+
when ALLOWANCE_MADE then [:conflict, Reason::VOID_BLOCKED_BY_ALLOWANCE]
|
|
47
|
+
when MISSING then [:not_found, nil]
|
|
48
|
+
else [:provider, nil]
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
@@ -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.items.map { |item| item.tax_type || parsed.tax_type }
|
|
32
|
+
check_tax!(types, parsed.tax_rate)
|
|
33
|
+
breakdown = parsed.tax_breakdown(provider: Client::PROVIDER)
|
|
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(provider: Client::PROVIDER)
|
|
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
|