einvoice 1.4.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 +12 -0
- data/.github/workflows/build.yml +7 -4
- data/CHANGELOG.md +55 -35
- data/Gemfile +3 -2
- data/README.md +230 -265
- data/README.zh-TW.md +322 -0
- data/Rakefile +2 -13
- data/bin/console +3 -6
- data/einvoice.gemspec +24 -21
- 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 -14
- 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 -10
- metadata +60 -176
- 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 -2022
- 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 -140
- data/lib/einvoice/tradevan/result.rb +0 -25
- data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
- data/lib/einvoice/utils.rb +0 -13
- data/lib/faraday/response/decode_tradevan.rb +0 -38
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
|
|
7
|
+
module Einvoice
|
|
8
|
+
module EzPay
|
|
9
|
+
# Speaks ezPay's wire protocol: a form POST of +MerchantID_+ and the
|
|
10
|
+
# encrypted +PostData_+, then the +Status+ / +Message+ / +Result+ answer.
|
|
11
|
+
# +Result+ is itself a JSON string, so it is parsed a second time.
|
|
12
|
+
class Client
|
|
13
|
+
PROVIDER = "ezpay"
|
|
14
|
+
BASE_URL = {
|
|
15
|
+
ProviderMode::TEST => "https://cinv.ezpay.com.tw",
|
|
16
|
+
ProviderMode::PRODUCTION => "https://inv.ezpay.com.tw"
|
|
17
|
+
}.freeze
|
|
18
|
+
SUCCESS = "SUCCESS"
|
|
19
|
+
|
|
20
|
+
attr_reader :merchant_id, :mode, :base_url, :timeout
|
|
21
|
+
|
|
22
|
+
def initialize(merchant_id:, hash_key:, hash_iv:, mode: ProviderMode::TEST, base_url: nil, timeout: 30,
|
|
23
|
+
clock: -> { Time.now })
|
|
24
|
+
if [merchant_id, hash_key, hash_iv].any? { |value| value.to_s.empty? }
|
|
25
|
+
raise ValidationError.new("ezPay merchant_id, hash_key and hash_iv are required", provider: PROVIDER)
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
@merchant_id = merchant_id.to_s
|
|
29
|
+
@hash_key = hash_key.to_s
|
|
30
|
+
@hash_iv = hash_iv.to_s
|
|
31
|
+
@mode = mode
|
|
32
|
+
@base_url = Redaction.base_url!(base_url || BASE_URL.fetch(mode) do
|
|
33
|
+
raise ValidationError.new("Unknown ezPay mode: #{mode.inspect}", provider: PROVIDER)
|
|
34
|
+
end, provider: PROVIDER)
|
|
35
|
+
@timeout = timeout
|
|
36
|
+
@clock = clock
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
def inspect
|
|
40
|
+
"#<#{self.class.name} merchant_id=#{@merchant_id.inspect} mode=#{@mode.inspect} " \
|
|
41
|
+
"base_url=#{@base_url.inspect} hash_key=#{Redaction::FILTERED} hash_iv=#{Redaction::FILTERED}>"
|
|
42
|
+
end
|
|
43
|
+
alias to_s inspect
|
|
44
|
+
|
|
45
|
+
# POST +fields+ to +path+ (for example +"/Api/invoice_issue"+) under the
|
|
46
|
+
# API +version+, and return the parsed +Result+ Hash. A +Status+ other
|
|
47
|
+
# than +SUCCESS+ raises; +operation+ picks the guesses in {Errors::CONTEXT}.
|
|
48
|
+
def request(path, version, fields, operation: nil)
|
|
49
|
+
payload = { "RespondType" => "JSON", "Version" => version, "TimeStamp" => @clock.call.to_i.to_s }
|
|
50
|
+
.merge(fields.transform_keys(&:to_s))
|
|
51
|
+
post_data = Crypto.encrypt(Crypto.build_query(payload), @hash_key, @hash_iv)
|
|
52
|
+
read(send_request(path, { "MerchantID_" => @merchant_id, "PostData_" => post_data }), operation)
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Raise {ProviderError} unless +result+ carries the CheckCode that the
|
|
56
|
+
# HashKey and HashIV give for it.
|
|
57
|
+
def verify_check_code!(result)
|
|
58
|
+
return if result["CheckCode"].to_s == Crypto.check_code(result, @hash_key, @hash_iv)
|
|
59
|
+
|
|
60
|
+
raise ProviderError.new("ezPay CheckCode does not match the result", provider: PROVIDER, raw: result)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
private
|
|
64
|
+
|
|
65
|
+
def send_request(path, form)
|
|
66
|
+
uri = URI("#{@base_url}#{path}")
|
|
67
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
68
|
+
http.use_ssl = uri.scheme == "https"
|
|
69
|
+
http.open_timeout = @timeout
|
|
70
|
+
http.read_timeout = @timeout
|
|
71
|
+
|
|
72
|
+
post = Net::HTTP::Post.new(uri.request_uri)
|
|
73
|
+
post.set_form_data(form)
|
|
74
|
+
response = nil
|
|
75
|
+
http.request(post) { |res| (response = res).read_body }
|
|
76
|
+
parse(response)
|
|
77
|
+
rescue *Error::NETWORK_ERRORS => e
|
|
78
|
+
raise NetworkError.for_failure(e, provider: PROVIDER, name: "ezPay", response: response)
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# A body that ezPay wrote (a JSON object with +Status+) decides the
|
|
82
|
+
# error, whatever the HTTP status. Any other body falls back to the
|
|
83
|
+
# status: HTTP 429 and 5xx are a NetworkError, so the caller can retry
|
|
84
|
+
# (docs/providers/README.md, "The unified model").
|
|
85
|
+
def parse(response)
|
|
86
|
+
body = JSON.parse(response.body.to_s)
|
|
87
|
+
return body if body.is_a?(Hash) && body.key?("Status")
|
|
88
|
+
|
|
89
|
+
raise_for_status!(response)
|
|
90
|
+
body
|
|
91
|
+
rescue JSON::ParserError => e
|
|
92
|
+
raise_for_status!(response)
|
|
93
|
+
raise ProviderError.new("ezPay returned a non-JSON response (HTTP #{response.code})",
|
|
94
|
+
provider: PROVIDER, raw_code: response.code, cause: e)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def raise_for_status!(response)
|
|
98
|
+
error = NetworkError.for_status(response, provider: PROVIDER)
|
|
99
|
+
raise error if error
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def read(body, operation)
|
|
103
|
+
unless body.is_a?(Hash) && body.key?("Status")
|
|
104
|
+
raise ProviderError.new("ezPay returned an unexpected response", provider: PROVIDER, raw: body)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
status = body["Status"].to_s
|
|
108
|
+
return parse_result(body) if status == SUCCESS
|
|
109
|
+
|
|
110
|
+
message = body["Message"].to_s
|
|
111
|
+
code, reason = Errors.classify(status, operation)
|
|
112
|
+
raise Einvoice::Error.for(code, message.empty? ? "ezPay returned #{status}" : message,
|
|
113
|
+
provider: PROVIDER, reason: reason, raw_code: status,
|
|
114
|
+
raw_message: message, raw: body)
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# +Result+ is a JSON string. It may also be empty, or already a Hash.
|
|
118
|
+
def parse_result(body)
|
|
119
|
+
result = body["Result"]
|
|
120
|
+
result = JSON.parse(result) if result.is_a?(String) && !result.strip.empty?
|
|
121
|
+
return result if result.is_a?(Hash)
|
|
122
|
+
return {} if result.nil? || result == ""
|
|
123
|
+
|
|
124
|
+
raise ProviderError.new("ezPay returned an unexpected Result", provider: PROVIDER, raw: body)
|
|
125
|
+
rescue JSON::ParserError => e
|
|
126
|
+
raise ProviderError.new("ezPay returned a Result that is not JSON", provider: PROVIDER, raw: body, cause: e)
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
end
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "digest"
|
|
5
|
+
|
|
6
|
+
module Einvoice
|
|
7
|
+
module EzPay
|
|
8
|
+
# The ezPay payload is a PHP +http_build_query+ string, padded with PKCS#7
|
|
9
|
+
# to a multiple of 32 bytes, encrypted with AES-256-CBC, and hex encoded
|
|
10
|
+
# (docs/providers/ezpay/invoice.md, section 2.2).
|
|
11
|
+
#
|
|
12
|
+
# Results carry a +CheckCode+: SHA-256 over five sorted result fields,
|
|
13
|
+
# wrapped in the HashIV and the HashKey (section 2.4).
|
|
14
|
+
module Crypto
|
|
15
|
+
BLOCK = 32
|
|
16
|
+
# PHP +urlencode+ keeps only these bytes. +rawurlencode+ also keeps +~+.
|
|
17
|
+
URLENCODE_KEEP = /[^a-zA-Z0-9\-_.]/n
|
|
18
|
+
RAWURLENCODE_KEEP = /[^a-zA-Z0-9\-_.~]/n
|
|
19
|
+
CHECK_FIELDS = %w[InvoiceTransNo MerchantID MerchantOrderNo RandomNum TotalAmt].freeze
|
|
20
|
+
|
|
21
|
+
module_function
|
|
22
|
+
|
|
23
|
+
# PHP +http_build_query+ over an ordered Hash: +urlencode+ on keys and
|
|
24
|
+
# values, so a space is +++.
|
|
25
|
+
def build_query(fields)
|
|
26
|
+
fields.map { |key, value| "#{urlencode(key)}=#{urlencode(value)}" }.join("&")
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# PHP +urlencode+.
|
|
30
|
+
def urlencode(value)
|
|
31
|
+
value.to_s.b.gsub(URLENCODE_KEEP) { |byte| byte == " " ? "+" : format("%%%02X", byte.ord) }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# PHP +rawurlencode+ (RFC 3986): a space is +%20+.
|
|
35
|
+
def rawurlencode(value)
|
|
36
|
+
value.to_s.b.gsub(RAWURLENCODE_KEEP) { |byte| format("%%%02X", byte.ord) }
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
# PHP +urldecode+, for reading a payload back (the fake uses it).
|
|
40
|
+
def urldecode(value)
|
|
41
|
+
value.to_s.tr("+", " ").b.gsub(/%([0-9A-Fa-f]{2})/) { ::Regexp.last_match(1).hex.chr }
|
|
42
|
+
.force_encoding(Encoding::UTF_8)
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def parse_query(query)
|
|
46
|
+
query.to_s.split("&").to_h do |pair|
|
|
47
|
+
key, value = pair.split("=", 2)
|
|
48
|
+
[urldecode(key), urldecode(value)]
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
# Query string → PostData_. PKCS#7 always adds padding, so a string that
|
|
53
|
+
# is already a multiple of 32 bytes gets a full block of 32.
|
|
54
|
+
def encrypt(plaintext, key, iv)
|
|
55
|
+
bytes = plaintext.to_s.b
|
|
56
|
+
pad = BLOCK - (bytes.bytesize % BLOCK)
|
|
57
|
+
cipher = new_cipher(key, iv, :encrypt)
|
|
58
|
+
(cipher.update(bytes + (pad.chr * pad)) + cipher.final).unpack1("H*")
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def decrypt(hex, key, iv)
|
|
62
|
+
cipher = new_cipher(key, iv, :decrypt)
|
|
63
|
+
bytes = cipher.update([hex.to_s].pack("H*")) + cipher.final
|
|
64
|
+
pad = bytes.empty? ? 0 : bytes.getbyte(-1)
|
|
65
|
+
raise ArgumentError, "bad padding" unless pad.between?(1, BLOCK) && bytes.bytesize >= pad
|
|
66
|
+
|
|
67
|
+
bytes[0...-pad].force_encoding(Encoding::UTF_8)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# The CheckCode of an issue or query result.
|
|
71
|
+
def check_code(result, key, iv)
|
|
72
|
+
joined = CHECK_FIELDS.sort.map { |field| "#{field}=#{result[field]}" }.join("&")
|
|
73
|
+
Digest::SHA256.hexdigest("HashIV=#{iv}&#{joined}&HashKey=#{key}").upcase
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def new_cipher(key, iv, direction)
|
|
77
|
+
cipher = OpenSSL::Cipher.new("aes-256-cbc").public_send(direction)
|
|
78
|
+
cipher.key = key.to_s.b
|
|
79
|
+
cipher.iv = iv.to_s.b
|
|
80
|
+
cipher.padding = 0
|
|
81
|
+
cipher
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module EzPay
|
|
5
|
+
# Maps ezPay's +Status+ codes onto the unified {Einvoice::Error} tree, from
|
|
6
|
+
# the code list in the manual (docs/providers/ezpay/invoice.md, section 6.4).
|
|
7
|
+
#
|
|
8
|
+
# The list has no code for an allowance on a voided invoice, for an
|
|
9
|
+
# allowance that does not exist, or for a duplicate allowance. {CONTEXT}
|
|
10
|
+
# holds our guesses for those cases, by operation, so that real codes can
|
|
11
|
+
# replace them in one place. Voiding an allowance twice has no code either.
|
|
12
|
+
# The fake assumes LIB10005, which the main table already reads as
|
|
13
|
+
# ConflictError.
|
|
14
|
+
module Errors
|
|
15
|
+
# code => [error class code, Reason or nil]
|
|
16
|
+
CODES = {
|
|
17
|
+
"KEY10002" => [:auth, Reason::CREDENTIALS_INVALID], # cannot decrypt
|
|
18
|
+
"KEY10004" => [:validation, nil], # data incomplete
|
|
19
|
+
"KEY10006" => [:auth, Reason::NOT_ENROLLED],
|
|
20
|
+
"KEY10007" => [:auth, Reason::STALE_TIMESTAMP], # open more than 30 minutes
|
|
21
|
+
"KEY10010" => [:validation, nil],
|
|
22
|
+
"KEY10011" => [:validation, nil],
|
|
23
|
+
"KEY10012" => [:provider, nil], # data transfer error
|
|
24
|
+
"KEY10013" => [:validation, nil],
|
|
25
|
+
"KEY10014" => [:network, nil], # timeout
|
|
26
|
+
"KEY10015" => [:validation, nil],
|
|
27
|
+
"INV10003" => [:validation, nil],
|
|
28
|
+
"INV10004" => [:validation, nil],
|
|
29
|
+
"INV10006" => [:validation, nil],
|
|
30
|
+
"INV10012" => [:validation, nil],
|
|
31
|
+
"INV10013" => [:validation, nil],
|
|
32
|
+
"INV10014" => [:validation, nil],
|
|
33
|
+
"INV10015" => [:validation, nil],
|
|
34
|
+
"INV10016" => [:validation, nil],
|
|
35
|
+
"INV10017" => [:validation, nil],
|
|
36
|
+
"INV10019" => [:validation, nil],
|
|
37
|
+
"INV10020" => [:auth, Reason::ACCOUNT_SUSPENDED],
|
|
38
|
+
"INV10021" => [:auth, Reason::ACCOUNT_SUSPENDED],
|
|
39
|
+
"INV20006" => [:not_found, nil],
|
|
40
|
+
"INV70001" => [:validation, nil],
|
|
41
|
+
"INV70002" => [:conflict, nil], # upload failed, cannot void
|
|
42
|
+
"INV90005" => [:auth, Reason::CONTRACT_EXPIRED],
|
|
43
|
+
"INV90006" => [:number_exhausted, nil],
|
|
44
|
+
"NOR10001" => [:network, nil],
|
|
45
|
+
"LIB10003" => [:conflict, Reason::DUPLICATE_ORDER],
|
|
46
|
+
"LIB10005" => [:conflict, Reason::ALREADY_VOIDED],
|
|
47
|
+
"LIB10007" => [:conflict, Reason::VOID_BLOCKED_BY_ALLOWANCE],
|
|
48
|
+
"LIB10008" => [:conflict, Reason::PAST_DEADLINE],
|
|
49
|
+
"LIB10009" => [:conflict, Reason::RETRY_LATER] # not uploaded yet, cannot void
|
|
50
|
+
}.freeze
|
|
51
|
+
|
|
52
|
+
# Guesses for the cases the code list does not cover. On an allowance,
|
|
53
|
+
# "already voided" means the invoice is voided, so nothing was credited.
|
|
54
|
+
# On an allowance void, IAI10002 (query failed) is the closest to "no
|
|
55
|
+
# such allowance".
|
|
56
|
+
CONTEXT = {
|
|
57
|
+
allowance: { "LIB10005" => [:conflict, Reason::ALLOWANCE_BLOCKED_BY_VOID] },
|
|
58
|
+
void_allowance: { "IAI10002" => [:not_found, nil] }
|
|
59
|
+
}.freeze
|
|
60
|
+
|
|
61
|
+
module_function
|
|
62
|
+
|
|
63
|
+
# @return [Array(Symbol, Symbol)] the error class code and the Reason
|
|
64
|
+
# (or nil). Unknown codes, and IAI10001 to IAI10006 outside the
|
|
65
|
+
# guesses above, are +:provider+.
|
|
66
|
+
def classify(code, operation = nil)
|
|
67
|
+
code = code.to_s
|
|
68
|
+
CONTEXT.fetch(operation, {})[code] || CODES[code] || [:provider, nil]
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Einvoice
|
|
4
|
+
module EzPay
|
|
5
|
+
# Maps the unified value model onto ezPay's payload fields, and checks the
|
|
6
|
+
# rules from docs/providers/ezpay/invoice.md locally, so a bad request fails
|
|
7
|
+
# before the network.
|
|
8
|
+
module Payload
|
|
9
|
+
TAX_TYPE = {
|
|
10
|
+
TaxType::TAXABLE => "1",
|
|
11
|
+
TaxType::ZERO_RATED => "2",
|
|
12
|
+
TaxType::TAX_FREE => "3"
|
|
13
|
+
}.freeze
|
|
14
|
+
MIXED_TAX_CODE = "9"
|
|
15
|
+
|
|
16
|
+
CARRIER_TYPE = {
|
|
17
|
+
CarrierType::MOBILE_BARCODE => "0",
|
|
18
|
+
CarrierType::CITIZEN_CERTIFICATE => "1",
|
|
19
|
+
CarrierType::MEMBER => "2" # ezPay's own member carrier
|
|
20
|
+
}.freeze
|
|
21
|
+
|
|
22
|
+
CONSUMER_NAME = "消費者"
|
|
23
|
+
DEFAULT_UNIT = "個"
|
|
24
|
+
VOID_ALLOWANCE_REASON = "作廢折讓"
|
|
25
|
+
# The rates TaxRate takes, as a percent (docs, section 4.2).
|
|
26
|
+
TAX_RATES = { 0r => "0", Rational(5, 100) => "5" }.freeze
|
|
27
|
+
ITEM_SEPARATOR = "|"
|
|
28
|
+
ORDER_ID = /\A[A-Za-z0-9_]{1,20}\z/
|
|
29
|
+
|
|
30
|
+
# [limit when the text is all ASCII, limit when it is not]
|
|
31
|
+
UNIT_LIMIT = [6, 2].freeze
|
|
32
|
+
REASON_LIMIT = [20, 6].freeze
|
|
33
|
+
|
|
34
|
+
module_function
|
|
35
|
+
|
|
36
|
+
# +invoice_issue+ fields from a parsed {IssueInvoiceInput}.
|
|
37
|
+
def issue(parsed)
|
|
38
|
+
b2b = parsed.resolved_category == InvoiceCategory::B2B
|
|
39
|
+
options = string_keys(parsed.provider_options)
|
|
40
|
+
types = parsed.items.map { |item| item.tax_type || parsed.tax_type }
|
|
41
|
+
mixed = types.uniq.size > 1
|
|
42
|
+
check_issue!(parsed, b2b, types, mixed)
|
|
43
|
+
|
|
44
|
+
breakdown = parsed.tax_breakdown(provider: Client::PROVIDER)
|
|
45
|
+
|
|
46
|
+
fields = {
|
|
47
|
+
"MerchantOrderNo" => parsed.order_id.to_s,
|
|
48
|
+
"Status" => "1",
|
|
49
|
+
"Category" => b2b ? "B2B" : "B2C",
|
|
50
|
+
"BuyerName" => buyer_name(parsed.buyer, b2b),
|
|
51
|
+
"BuyerUBN" => b2b ? parsed.buyer.ubn.to_s : "",
|
|
52
|
+
"BuyerAddress" => parsed.buyer&.address.to_s,
|
|
53
|
+
"BuyerEmail" => parsed.buyer&.email.to_s,
|
|
54
|
+
**carrier_fields(parsed.carrier, parsed.buyer),
|
|
55
|
+
"LoveCode" => parsed.donation&.npoban.to_s,
|
|
56
|
+
"PrintFlag" => b2b || (parsed.carrier.nil? && parsed.donation.nil?) ? "Y" : "N",
|
|
57
|
+
"TaxType" => mixed ? MIXED_TAX_CODE : TAX_TYPE.fetch(types.first),
|
|
58
|
+
"TaxRate" => TAX_RATES.fetch(parsed.tax_rate)
|
|
59
|
+
}
|
|
60
|
+
# ezPay has no field for zero_tax_rate_reason (docs, section 4.6).
|
|
61
|
+
fields["CustomsClearance"] = parsed.customs_clearance_mark if parsed.zero_rated?
|
|
62
|
+
fields.merge!(issue_amounts(breakdown, mixed))
|
|
63
|
+
fields.merge!(item_fields(parsed.items, breakdown.lines, net: b2b))
|
|
64
|
+
fields["ItemTaxType"] = types.map { |type| TAX_TYPE.fetch(type) }.join(ITEM_SEPARATOR) if mixed
|
|
65
|
+
fields["Comment"] = parsed.remark.to_s
|
|
66
|
+
fields
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# +invoice_invalid+ fields.
|
|
70
|
+
def void(parsed)
|
|
71
|
+
{ "InvoiceNumber" => parsed.invoice.number.to_s, "InvalidReason" => reason!(parsed.reason) }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# +allowance_issue+ fields. Confirmed at once (+Status+ 1). +original+
|
|
75
|
+
# has the invoice's +order_id+, and +business+ says if its buyer has a
|
|
76
|
+
# 統一編號 (section 4.3).
|
|
77
|
+
def allowance(parsed, original)
|
|
78
|
+
options = string_keys(parsed.provider_options)
|
|
79
|
+
check_rate!(parsed.tax_rate)
|
|
80
|
+
breakdown = parsed.tax_breakdown(provider: Client::PROVIDER)
|
|
81
|
+
refuse_special!(breakdown.lines.map(&:tax_type))
|
|
82
|
+
|
|
83
|
+
fields = { "InvoiceNo" => parsed.invoice.number.to_s, "MerchantOrderNo" => original[:order_id].to_s }
|
|
84
|
+
fields.merge!(item_fields(parsed.items, breakdown.lines, net: original[:business]))
|
|
85
|
+
fields["ItemTaxAmt"] = breakdown.lines.map { |line| original[:business] ? line.tax : 0 }.join(ITEM_SEPARATOR)
|
|
86
|
+
fields["TotalAmt"] = parsed.amount.total_amount
|
|
87
|
+
fields["TaxTypeForMixed"] = options["tax_type_for_mixed"].to_s if options.key?("tax_type_for_mixed")
|
|
88
|
+
fields["BuyerEmail"] = options["buyer_email"].to_s if options.key?("buyer_email")
|
|
89
|
+
fields["Status"] = "1"
|
|
90
|
+
fields
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
# +allowanceInvalid+ fields.
|
|
94
|
+
def void_allowance(parsed)
|
|
95
|
+
{ "AllowanceNo" => parsed.allowance.allowance_number.to_s,
|
|
96
|
+
"InvalidReason" => reason!(parsed.reason || VOID_ALLOWANCE_REASON) }
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# +invoice_search+ fields, by number. ezPay needs the random code with
|
|
100
|
+
# it. A query by order id needs the total, so the adapter does not offer
|
|
101
|
+
# it (section 4.6).
|
|
102
|
+
def query(reference)
|
|
103
|
+
invalid!("an ezPay query needs invoice.random_code with the number") unless queryable?(reference)
|
|
104
|
+
|
|
105
|
+
{ "SearchType" => "0", "InvoiceNumber" => reference.number.to_s, "RandomNum" => reference.random_code.to_s }
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Whether +reference+ has the two keys of a query by number.
|
|
109
|
+
def queryable?(reference)
|
|
110
|
+
!reference.number.nil? && !reference.random_code.nil?
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# --- issue -------------------------------------------------------------
|
|
114
|
+
|
|
115
|
+
def check_issue!(parsed, b2b, types, mixed)
|
|
116
|
+
unless parsed.order_id.to_s.match?(ORDER_ID)
|
|
117
|
+
unsupported!("ezPay takes an order_id of 1 to 20 letters, digits or _")
|
|
118
|
+
end
|
|
119
|
+
max!(parsed.buyer&.email.to_s, 50, "buyer email")
|
|
120
|
+
refuse_special!(types)
|
|
121
|
+
unsupported!("ezPay allows mixed tax only on a B2C invoice") if mixed && b2b
|
|
122
|
+
# The MIG allows a carrier and a donation on a B2B invoice, and a carrier
|
|
123
|
+
# with a donation. ezPay refuses all three.
|
|
124
|
+
unsupported!("ezPay takes a donation only on a B2C invoice") if b2b && parsed.donation
|
|
125
|
+
unsupported!("ezPay takes a carrier only on a B2C invoice") if b2b && parsed.carrier
|
|
126
|
+
unsupported!("ezPay does not take a carrier together with a donation") if parsed.carrier && parsed.donation
|
|
127
|
+
check_rate!(parsed.tax_rate)
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def refuse_special!(types)
|
|
131
|
+
return unless types.include?(TaxType::SPECIAL)
|
|
132
|
+
|
|
133
|
+
raise UnsupportedError.new("ezPay adapter does not support special tax (特種稅額)", provider: Client::PROVIDER)
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# The core has checked that +rate+ is a MIG rate. ezPay takes two of them.
|
|
137
|
+
def check_rate!(rate)
|
|
138
|
+
return if TAX_RATES.key?(rate)
|
|
139
|
+
|
|
140
|
+
raise UnsupportedError.new("ezPay takes a tax rate of 0 or 0.05 only, got #{rate.to_f}",
|
|
141
|
+
provider: Client::PROVIDER)
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# ezPay always splits the tax out: +Amt+ excludes it (section 4.3). The
|
|
145
|
+
# split is the core's.
|
|
146
|
+
def issue_amounts(breakdown, mixed)
|
|
147
|
+
fields = { "Amt" => breakdown.sales_amount, "TaxAmt" => breakdown.tax_amount,
|
|
148
|
+
"TotalAmt" => breakdown.total_amount }
|
|
149
|
+
if mixed
|
|
150
|
+
fields["AmtSales"] = breakdown.taxable_amount
|
|
151
|
+
fields["AmtZero"] = breakdown.zero_rated_amount
|
|
152
|
+
fields["AmtFree"] = breakdown.tax_free_amount
|
|
153
|
+
end
|
|
154
|
+
fields
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def buyer_name(buyer, b2b)
|
|
158
|
+
name = buyer&.name.to_s
|
|
159
|
+
if b2b
|
|
160
|
+
return name unless name.empty?
|
|
161
|
+
|
|
162
|
+
return buyer.ubn.to_s
|
|
163
|
+
end
|
|
164
|
+
return CONSUMER_NAME if name.empty?
|
|
165
|
+
|
|
166
|
+
max!(name, 30, "buyer name")
|
|
167
|
+
name
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# +CarrierNum+ is +rawurlencode+d before the query string encodes it again
|
|
171
|
+
# (section 2.2). A member carrier without a code uses the buyer's email.
|
|
172
|
+
def carrier_fields(carrier, buyer)
|
|
173
|
+
return { "CarrierType" => "", "CarrierNum" => "" } unless carrier
|
|
174
|
+
|
|
175
|
+
code = carrier.code.to_s
|
|
176
|
+
code = buyer&.email.to_s if code.empty? && carrier.type == CarrierType::MEMBER
|
|
177
|
+
invalid!("a #{carrier.type} carrier needs a code") if code.empty?
|
|
178
|
+
max!(code, 50, "carrier code")
|
|
179
|
+
|
|
180
|
+
{ "CarrierType" => CARRIER_TYPE.fetch(carrier.type), "CarrierNum" => Crypto.rawurlencode(code) }
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# --- items -------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
# Each item field is one string, items separated by +|+. ezPay fixes the
|
|
186
|
+
# prices by the buyer (section 4.3): without tax for a business (+net+),
|
|
187
|
+
# with tax for a consumer. Both come from the core's lines, so the
|
|
188
|
+
# input's +price_mode+ does not matter.
|
|
189
|
+
def item_fields(items, lines, net:)
|
|
190
|
+
rows = items.zip(lines).map { |item, line| item_row(item, net ? line.net_amount : line.gross_amount) }
|
|
191
|
+
%w[ItemName ItemCount ItemUnit ItemPrice ItemAmt].to_h do |field|
|
|
192
|
+
[field, rows.map { |row| row[field] }.join(ITEM_SEPARATOR)]
|
|
193
|
+
end
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
# ezPay wants +ItemAmt = ItemCount × ItemPrice+ in whole numbers, so the
|
|
197
|
+
# price is the amount over the count, and it has to divide.
|
|
198
|
+
def item_row(item, amount)
|
|
199
|
+
name = item.description.to_s
|
|
200
|
+
unit = item.unit.to_s.empty? ? DEFAULT_UNIT : item.unit.to_s
|
|
201
|
+
[name, unit].each do |text|
|
|
202
|
+
unsupported!("ezPay item text must not contain |: #{text.inspect}") if text.include?("|")
|
|
203
|
+
end
|
|
204
|
+
max!(name, 30, "item description")
|
|
205
|
+
limited!(unit, UNIT_LIMIT, "item unit")
|
|
206
|
+
|
|
207
|
+
count = integer!(item.quantity, "item quantity")
|
|
208
|
+
unsupported!("ezPay needs an item quantity above 0, got #{count}") unless count.positive?
|
|
209
|
+
amount = integer!(amount, "item amount")
|
|
210
|
+
unless (amount % count).zero?
|
|
211
|
+
unsupported!("ezPay needs a whole unit price, but the item amount #{amount} does not divide by #{count}")
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
{ "ItemName" => name, "ItemCount" => count, "ItemUnit" => unit, "ItemPrice" => amount / count,
|
|
215
|
+
"ItemAmt" => amount }
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
# --- allowance ---------------------------------------------------------
|
|
219
|
+
|
|
220
|
+
# --- helpers -----------------------------------------------------------
|
|
221
|
+
|
|
222
|
+
def reason!(reason)
|
|
223
|
+
text = reason.to_s
|
|
224
|
+
invalid!("reason is required") if text.empty?
|
|
225
|
+
limited!(text, REASON_LIMIT, "reason")
|
|
226
|
+
text
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
# ezPay counts "2 Chinese or 6 English characters". A text with any
|
|
230
|
+
# non-ASCII character gets the Chinese limit. The ASCII limits are the
|
|
231
|
+
# MIG's, which the core checks, so only the shorter limit is left here.
|
|
232
|
+
def limited!(text, (ascii, other), field)
|
|
233
|
+
max!(text, text.ascii_only? ? ascii : other, field)
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# The core reads every number as exact, but allows decimals. ezPay does
|
|
237
|
+
# not.
|
|
238
|
+
def integer!(value, field)
|
|
239
|
+
rational = value.to_r
|
|
240
|
+
return rational.to_i if rational.denominator == 1
|
|
241
|
+
|
|
242
|
+
unsupported!("ezPay needs a whole number for #{field}, got #{Number.plain(rational)}")
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
# The core checks the MIG lengths. A shorter limit of ezPay's own is
|
|
246
|
+
# UnsupportedError: another provider may take the value
|
|
247
|
+
# (docs/providers/README.md, "The unified model").
|
|
248
|
+
def max!(value, limit, field)
|
|
249
|
+
return if value.length <= limit
|
|
250
|
+
|
|
251
|
+
unsupported!("ezPay takes a #{field} of at most #{limit} characters")
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# The input breaks a MIG rule, or lacks what the call needs.
|
|
255
|
+
def invalid!(message)
|
|
256
|
+
raise ValidationError.new(message, provider: Client::PROVIDER)
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
# The MIG allows the input, but ezPay does not take it.
|
|
260
|
+
def unsupported!(message)
|
|
261
|
+
raise UnsupportedError.new(message, provider: Client::PROVIDER)
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
def string_keys(hash)
|
|
265
|
+
(hash || {}).to_h.transform_keys(&:to_s)
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
end
|
|
269
|
+
end
|