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.
Files changed (66) hide show
  1. checksums.yaml +4 -4
  2. data/.coderabbit.yaml +12 -0
  3. data/.github/workflows/build.yml +7 -4
  4. data/CHANGELOG.md +55 -35
  5. data/Gemfile +3 -2
  6. data/README.md +230 -265
  7. data/README.zh-TW.md +322 -0
  8. data/Rakefile +2 -13
  9. data/bin/console +3 -6
  10. data/einvoice.gemspec +24 -21
  11. data/lib/einvoice/amego/client.rb +116 -0
  12. data/lib/einvoice/amego/errors.rb +84 -0
  13. data/lib/einvoice/amego/payload.rb +276 -0
  14. data/lib/einvoice/amego/provider.rb +267 -0
  15. data/lib/einvoice/amego.rb +27 -0
  16. data/lib/einvoice/capability.rb +79 -0
  17. data/lib/einvoice/ecpay/client.rb +183 -0
  18. data/lib/einvoice/ecpay/crypto.rb +85 -0
  19. data/lib/einvoice/ecpay/errors.rb +115 -0
  20. data/lib/einvoice/ecpay/payload.rb +241 -0
  21. data/lib/einvoice/ecpay/provider.rb +362 -0
  22. data/lib/einvoice/ecpay.rb +31 -0
  23. data/lib/einvoice/error.rb +220 -0
  24. data/lib/einvoice/ezpay/client.rb +130 -0
  25. data/lib/einvoice/ezpay/crypto.rb +85 -0
  26. data/lib/einvoice/ezpay/errors.rb +72 -0
  27. data/lib/einvoice/ezpay/payload.rb +269 -0
  28. data/lib/einvoice/ezpay/provider.rb +235 -0
  29. data/lib/einvoice/ezpay.rb +19 -0
  30. data/lib/einvoice/input.rb +494 -0
  31. data/lib/einvoice/mock_provider.rb +191 -0
  32. data/lib/einvoice/mof/donation_codes.rb +157 -0
  33. data/lib/einvoice/mof.rb +16 -0
  34. data/lib/einvoice/number.rb +51 -0
  35. data/lib/einvoice/provider.rb +57 -14
  36. data/lib/einvoice/redaction.rb +54 -0
  37. data/lib/einvoice/taipei.rb +89 -0
  38. data/lib/einvoice/tax_split.rb +124 -0
  39. data/lib/einvoice/tradevan/default_api/client.rb +175 -0
  40. data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
  41. data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
  42. data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
  43. data/lib/einvoice/tradevan/default_api/provider.rb +366 -0
  44. data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
  45. data/lib/einvoice/tradevan.rb +25 -0
  46. data/lib/einvoice/types.rb +323 -0
  47. data/lib/einvoice/version.rb +3 -1
  48. data/lib/einvoice.rb +21 -10
  49. metadata +60 -176
  50. data/.github/workflows/cron.yml +0 -31
  51. data/docs/Tradevan E-Invoice APIs.md +0 -201
  52. data/docs/neweb.md +0 -347
  53. data/lib/einvoice/client.rb +0 -21
  54. data/lib/einvoice/configuration.rb +0 -49
  55. data/lib/einvoice/connection.rb +0 -31
  56. data/lib/einvoice/donation_unit_list.json +0 -2022
  57. data/lib/einvoice/result.rb +0 -21
  58. data/lib/einvoice/tradevan/model/base.rb +0 -34
  59. data/lib/einvoice/tradevan/model/issue_data.rb +0 -129
  60. data/lib/einvoice/tradevan/model/issue_item.rb +0 -41
  61. data/lib/einvoice/tradevan/model/void_data.rb +0 -35
  62. data/lib/einvoice/tradevan/provider.rb +0 -140
  63. data/lib/einvoice/tradevan/result.rb +0 -25
  64. data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
  65. data/lib/einvoice/utils.rb +0 -13
  66. data/lib/faraday/response/decode_tradevan.rb +0 -38
@@ -0,0 +1,157 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+ require "json"
6
+
7
+ module Einvoice
8
+ module MOF
9
+ # 受捐贈機關或團體 as published by 財政部. A lookup result, not part of an
10
+ # invoice — {Einvoice::Donation} is what you put on one.
11
+ DonationCode = Data.define(:code, :name, :short_name, :ubn, :city, :raw)
12
+
13
+ # Reads 財政部's 捐贈碼 dataset over its public ODS API — the authority for
14
+ # whether a 愛心碼 is real, and provider-independent, so it works whatever
15
+ # value-added center you issue through.
16
+ #
17
+ # codes = Einvoice::MOF::DonationCodes.new
18
+ # codes.lookup("2718") # => #<data DonationCode code="2718", name="社團法人台北市喜願協會", …>
19
+ # codes.exist?("105") # => false
20
+ #
21
+ # Deliberately not wired into {Einvoice::Input}: validation there is local and
22
+ # synchronous, and an issue call must never depend on a third party being up.
23
+ # Call this when it suits you — at order time, or once at boot via {#all} to
24
+ # build your own set, which costs five requests for the whole dataset.
25
+ #
26
+ # No credentials are needed today. The published OpenAPI declares +api_key+
27
+ # and +oauth2+ schemes even though the endpoint answers anonymously, so that
28
+ # could change; a 401/403 surfaces as {Einvoice::AuthError} saying exactly
29
+ # that rather than as a confusing parse failure.
30
+ class DonationCodes
31
+ PROVIDER = "mof"
32
+ BASE_URL = "https://dataset.einvoice.nat.gov.tw/ods/portal"
33
+ PATH = "/api/v1/DonateCodeList"
34
+
35
+ # The same shape {Einvoice::Donation} defines, deliberately shared: a code
36
+ # this client accepts is one you can put on an invoice.
37
+ CODE_FORMAT = Donation::CODE_FORMAT
38
+ # The API's documented ceiling; the dataset is ~2,000 rows, so a full sweep
39
+ # is a handful of requests.
40
+ MAX_PAGE = 500
41
+ # Backstop so a misbehaving endpoint can't spin {#all} forever.
42
+ MAX_PAGES = 100
43
+
44
+ def initialize(base_url: BASE_URL, timeout: 30)
45
+ @base_url = Redaction.base_url!(base_url, provider: PROVIDER)
46
+ @timeout = timeout
47
+ end
48
+
49
+ # The registered organisation for a 愛心碼, or +nil+ when the code is not in
50
+ # the dataset. Raises {ValidationError} if it isn't 3–7 digits.
51
+ #
52
+ # The donateCode filter is not in the OpenAPI file, so its match rule is
53
+ # not known. Only a row with exactly this code counts.
54
+ def lookup(code)
55
+ assert_format!(code)
56
+ row = get(donateCode: code).find { |r| r["donateCode"].to_s == code.to_s }
57
+ row && build(row)
58
+ end
59
+
60
+ # Whether a 愛心碼 is registered.
61
+ def exist?(code)
62
+ !lookup(code).nil?
63
+ end
64
+
65
+ # Every code registered to a 統一編號 — an organisation may hold more than one.
66
+ def for_ubn(ubn)
67
+ unless ubn.to_s.match?(/\A\d{8}\z/)
68
+ raise ValidationError.new("統一編號 must be 8 digits, got #{ubn.inspect}", provider: PROVIDER)
69
+ end
70
+
71
+ get(donateBan: ubn).map { |row| build(row) }
72
+ end
73
+
74
+ # The whole dataset, paged. Callers who want offline validation should hold
75
+ # onto this rather than calling {#lookup} per code.
76
+ def all
77
+ rows = []
78
+ MAX_PAGES.times do
79
+ page = get(limit: MAX_PAGE, offset: rows.size)
80
+ rows.concat(page)
81
+ break if page.size < MAX_PAGE
82
+ end
83
+ rows.map { |row| build(row) }
84
+ end
85
+
86
+ private
87
+
88
+ def assert_format!(code)
89
+ return if code.to_s.match?(CODE_FORMAT)
90
+
91
+ raise ValidationError.new("愛心碼 must be 3–7 digits, got #{code.inspect}",
92
+ provider: PROVIDER)
93
+ end
94
+
95
+ def build(row)
96
+ DonationCode.new(
97
+ code: row["donateCode"].to_s,
98
+ name: row["donateNm"].to_s,
99
+ short_name: presence(row["donateShortNm"]),
100
+ ubn: presence(row["donateBan"]),
101
+ city: presence(row["hsnNm"]),
102
+ raw: row
103
+ )
104
+ end
105
+
106
+ def get(params)
107
+ uri = URI("#{@base_url}#{PATH}")
108
+ uri.query = URI.encode_www_form(params)
109
+ parse(fetch(uri))
110
+ end
111
+
112
+ def fetch(uri)
113
+ http = Net::HTTP.new(uri.host, uri.port)
114
+ http.use_ssl = uri.scheme == "https"
115
+ http.open_timeout = @timeout
116
+ http.read_timeout = @timeout
117
+ response = http.request(Net::HTTP::Get.new(uri.request_uri))
118
+ check!(response)
119
+ response
120
+ rescue *Error::NETWORK_ERRORS => e
121
+ raise NetworkError.new("財政部 request failed: #{e.message}", provider: PROVIDER, cause: e)
122
+ end
123
+
124
+ # The endpoint is open today but is documented with auth schemes, so name
125
+ # that case instead of letting it read as a malformed response.
126
+ def check!(response)
127
+ case response.code.to_i
128
+ when 200 then nil
129
+ when 429, 500..599 then raise NetworkError.for_status(response, provider: PROVIDER)
130
+ when 401, 403
131
+ raise AuthError.new(
132
+ "財政部 now requires credentials for the donation-code dataset (HTTP #{response.code})",
133
+ provider: PROVIDER, reason: Reason::CREDENTIALS_INVALID, raw_code: response.code
134
+ )
135
+ else
136
+ raise ProviderError.new("財政部 returned HTTP #{response.code}", provider: PROVIDER,
137
+ raw_code: response.code)
138
+ end
139
+ end
140
+
141
+ def parse(response)
142
+ body = JSON.parse(response.body.to_s)
143
+ return body if body.is_a?(Array)
144
+
145
+ raise ProviderError.new("財政部 returned an unexpected payload", provider: PROVIDER,
146
+ raw: body)
147
+ rescue JSON::ParserError => e
148
+ raise ProviderError.new("財政部 returned a non-JSON response", provider: PROVIDER, cause: e)
149
+ end
150
+
151
+ def presence(value)
152
+ string = value.to_s
153
+ string.empty? ? nil : string
154
+ end
155
+ end
156
+ end
157
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "einvoice"
4
+ require "einvoice/mof/donation_codes"
5
+
6
+ module Einvoice
7
+ # Direct clients for 財政部's own public services — the authority every
8
+ # value-added center ultimately files to.
9
+ #
10
+ # These are not {Einvoice::Provider}s: they issue nothing, hold no merchant
11
+ # credentials, and are provider-independent, so they work whichever center you
12
+ # issue through (and when you haven't chosen one yet). Everything here is
13
+ # opt-in and called explicitly; nothing on the issue path reaches for it.
14
+ module MOF
15
+ end
16
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Einvoice
4
+ # Number checks for MIG fields. Amounts on an item may have up to 7 decimal
5
+ # places (MIG 表 15-5). Totals are whole TWD.
6
+ module Number
7
+ DECIMAL_PLACES = 7
8
+ DECIMAL = /\A-?\d+(\.\d+)?\z/
9
+
10
+ module_function
11
+
12
+ # A Rational for a number with at most 7 decimal places. Accepts Integer,
13
+ # Rational, BigDecimal, Float and numeric strings. Float goes through its
14
+ # string form, so 0.1 stays 1/10 and does not become a binary fraction.
15
+ def decimal!(value, field:, provider: nil)
16
+ rational = to_rational(value)
17
+ invalid!("#{field} must be a number, got #{value.inspect}", provider) if rational.nil?
18
+ if (rational * (10**DECIMAL_PLACES)).denominator != 1
19
+ invalid!("#{field} may have at most #{DECIMAL_PLACES} decimal places, got #{value.inspect}", provider)
20
+ end
21
+ rational
22
+ end
23
+
24
+ def integer!(value, field:, provider: nil)
25
+ rational = to_rational(value)
26
+ if rational.nil? || rational.denominator != 1
27
+ invalid!("#{field} must be a whole number, got #{value.inspect}", provider)
28
+ end
29
+ rational.to_i
30
+ end
31
+
32
+ def to_rational(value)
33
+ case value
34
+ when Integer, Rational then value.to_r
35
+ when Float then value.finite? ? Rational(value.to_s) : nil
36
+ when Numeric then value.to_r
37
+ when String then value.strip.match?(DECIMAL) ? Rational(value.strip) : nil
38
+ end
39
+ end
40
+
41
+ # An Integer when the value is whole, else a Float, so an amount serializes
42
+ # as 95 or 47.5 and not as a Rational.
43
+ def plain(value)
44
+ value.denominator == 1 ? value.to_i : value.to_f
45
+ end
46
+
47
+ def invalid!(message, provider)
48
+ raise ValidationError.new(message, provider: provider || "einvoice")
49
+ end
50
+ end
51
+ end
@@ -1,23 +1,66 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Einvoice
4
+ # The contract every provider adapter implements. Application code depends on
5
+ # this base, never on a concrete adapter, so providers are swappable — switching
6
+ # is a one-line constructor change.
7
+ #
8
+ # All five operations raise an {Einvoice::Error} on failure. Subclasses must
9
+ # implement {#name}, {#capabilities}, and the five operations; {#supports?} and
10
+ # {#assert_supports!} come from {Capability::Support}.
2
11
  class Provider
3
- attr_accessor *Configuration::VALID_OPTIONS_KEYS
4
- attr_accessor :provider
12
+ include Capability::Support
13
+
14
+ # A stable identifier, e.g. "amego", "ecpay".
15
+ def name
16
+ raise NotImplementedError, "#{self.class} must implement #name"
17
+ end
18
+
19
+ # The set of optional features this adapter declares (a Set of
20
+ # {Capability} symbols).
21
+ def capabilities
22
+ raise NotImplementedError, "#{self.class} must implement #capabilities"
23
+ end
24
+
25
+ # 開立發票.
26
+ def issue(_input)
27
+ raise NotImplementedError, "#{self.class} must implement #issue"
28
+ end
5
29
 
6
- def initialize(options={})
7
- options = Einvoice.options.merge(options)
8
- Configuration::VALID_OPTIONS_KEYS.each do |key|
9
- send("#{key}=", options[key])
10
- end
30
+ # 作廢發票.
31
+ def void(_input)
32
+ raise NotImplementedError, "#{self.class} must implement #void"
11
33
  end
12
34
 
13
- def config
14
- conf = {}
15
- Configuration::VALID_OPTIONS_KEYS.each do |key|
16
- conf[key] = send key
17
- end
18
- conf
35
+ # 開立折讓.
36
+ def allowance(_input)
37
+ raise NotImplementedError, "#{self.class} must implement #allowance"
19
38
  end
20
39
 
21
- include Connection
40
+ # 作廢折讓.
41
+ def void_allowance(_input)
42
+ raise NotImplementedError, "#{self.class} must implement #void_allowance"
43
+ end
44
+
45
+ # The {InvoiceStatus} values that {#query} can return. Any other invoice
46
+ # queries as +nil+. A provider whose status cannot show every state lists
47
+ # fewer, so a caller can check before it relies on one: code that reconciles
48
+ # voids needs +InvoiceStatus::VOIDED+ here.
49
+ def query_statuses
50
+ InvoiceStatus::ALL
51
+ end
52
+
53
+ # 查詢發票.
54
+ def query(_input)
55
+ raise NotImplementedError, "#{self.class} must implement #query"
56
+ end
57
+
58
+ # Whether a carrier is registered with the MOF. Takes a {Carrier} or a Hash
59
+ # of its fields. Raises UnsupportedError unless the provider declares
60
+ # CARRIER_VALIDATION, or when it cannot check this type of carrier.
61
+ def validate_carrier(_carrier)
62
+ assert_supports!(Capability::CARRIER_VALIDATION)
63
+ raise NotImplementedError, "#{self.class} must implement #validate_carrier"
64
+ end
22
65
  end
23
66
  end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Einvoice
6
+ # Keeps credentials, buyer data and plain-HTTP traffic out of places where
7
+ # they leak: inspect output (logs, consoles, error trackers) and the network.
8
+ module Redaction
9
+ FILTERED = "[FILTERED]"
10
+
11
+ # For value types with a +raw+ field. +raw+ is the provider's response, and
12
+ # it holds the buyer's name, address, email and phone, so inspect and pp
13
+ # show it as [FILTERED]. Read +#raw+ directly when you need it.
14
+ module Raw
15
+ def inspect
16
+ fields = to_h.map { |key, value| "#{key}=#{key == :raw ? FILTERED : value.inspect}" }
17
+ "#<data #{self.class.name} #{fields.join(', ')}>"
18
+ end
19
+ alias to_s inspect
20
+
21
+ def pretty_print(printer)
22
+ printer.text(inspect)
23
+ end
24
+ end
25
+
26
+ LOCALHOST = %w[localhost 127.0.0.1 ::1 [::1]].freeze
27
+
28
+ module_function
29
+
30
+ # A base URL for a provider. It has to use https. Only localhost may use
31
+ # http, for tests. Credentials and buyer data must not go over plain HTTP.
32
+ # It must not carry userinfo either, because Client#inspect prints the base URL.
33
+ # A query or a fragment is refused: a client appends its path, so
34
+ # +https://host/gw?a=1+ would send +/gw?a=1/path+ to the wrong place.
35
+ #
36
+ # Returns the URL without a trailing slash, frozen, so a client can append
37
+ # a path and nobody can change it after the checks.
38
+ def base_url!(url, provider:)
39
+ uri = URI.parse(url.to_s)
40
+ raise ValidationError.new("base_url must not contain a user or password", provider: provider) if uri.userinfo
41
+ if uri.query || uri.fragment
42
+ raise ValidationError.new("base_url must not contain a query or a fragment", provider: provider)
43
+ end
44
+ return url.to_s.chomp("/").freeze if uri.scheme == "https" && !uri.host.to_s.empty?
45
+ return url.to_s.chomp("/").freeze if uri.scheme == "http" && LOCALHOST.include?(uri.host)
46
+
47
+ raise ValidationError.new("base_url must use https (http is allowed for localhost only), got #{url}",
48
+ provider: provider)
49
+ rescue URI::InvalidURIError
50
+ # Not the URL itself: a malformed one may still hold a password.
51
+ raise ValidationError.new("base_url is not a valid URL", provider: provider)
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module Einvoice
6
+ # Taipei time (UTC+8). Taiwan has no daylight saving time, so a fixed offset
7
+ # is correct. The MIG reads every date and time in UTC+8.
8
+ #
9
+ # Adapters use this module and do not call Date#to_time. Date#to_time uses the
10
+ # host time zone, so on a host east of UTC+8 it gives the day before.
11
+ module Taipei
12
+ OFFSET = "+08:00"
13
+ # A date and time with an offset: ISO 8601 (2026-08-01T10:00:00+08:00, or Z)
14
+ # or Time#to_s (2026-08-01 10:00:00 +0800). A string without an offset is
15
+ # refused, so a stored time is never read in the wrong zone.
16
+ ZONED_TIME = /\A(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2}):(\d{2})(\.\d+)? ?(Z|[+-]\d{2}:?\d{2})\z/
17
+ # A calendar date, read as that day in Taipei.
18
+ DATE = /\A(\d{4})-(\d{2})-(\d{2})\z/
19
+
20
+ module_function
21
+
22
+ # The current Taipei time. +clock+ is anything that answers #now.
23
+ def now(clock = Time)
24
+ clock.now.getlocal(OFFSET)
25
+ end
26
+
27
+ def today(clock = Time)
28
+ now(clock).to_date
29
+ end
30
+
31
+ # A Time in Taipei. A Date becomes midnight in Taipei. A String has to match
32
+ # ZONED_TIME or DATE.
33
+ def time(value, field: "time", provider: nil)
34
+ value = parse(value, field, provider) if value.is_a?(String)
35
+ case value
36
+ when DateTime then value.to_time.getlocal(OFFSET)
37
+ when Date then Time.new(value.year, value.month, value.day, 0, 0, 0, OFFSET)
38
+ when Time then value.getlocal(OFFSET)
39
+ else invalid!("#{field} must be a Time or a Date, got #{value.class}", provider)
40
+ end
41
+ end
42
+
43
+ # The Taipei calendar date of a Time, or the Date itself. A String has to
44
+ # match ZONED_TIME or DATE.
45
+ def date(value, field: "date", provider: nil)
46
+ value = parse(value, field, provider) if value.is_a?(String)
47
+ case value
48
+ when DateTime then value.to_time.getlocal(OFFSET).to_date
49
+ when Date then value
50
+ when Time then value.getlocal(OFFSET).to_date
51
+ else invalid!("#{field} must be a Date or a Time, got #{value.class}", provider)
52
+ end
53
+ end
54
+
55
+ # The stored form of a time: ISO 8601 in Taipei, with fractional seconds
56
+ # only when it has them. +time+ reads it back unchanged.
57
+ def iso8601(value)
58
+ value = time(value)
59
+ format = value.subsec.zero? ? "%Y-%m-%dT%H:%M:%S%:z" : "%Y-%m-%dT%H:%M:%S.%N%:z"
60
+ value.strftime(format)
61
+ end
62
+
63
+ def parse(string, field, provider)
64
+ if (match = ZONED_TIME.match(string))
65
+ year, month, day, hour, minute, second, fraction, zone = match.captures
66
+ seconds = second.to_i + (fraction ? Rational(fraction[1..].to_i, 10**(fraction.length - 1)) : 0)
67
+ zone = zone == "Z" ? "UTC" : zone.sub(/(\d{2})(\d{2})\z/, '\1:\2')
68
+ fields = [year, month, day, hour, minute, second].map(&:to_i)
69
+ time = Time.new(*fields[0, 5], seconds, zone)
70
+ # Time.new rolls an impossible value over (Feb 30 becomes Mar 2, 24:00
71
+ # the next day), so a stored typo would name another day. Refuse it.
72
+ raise ArgumentError unless [time.year, time.month, time.day, time.hour, time.min, time.sec] == fields
73
+
74
+ time
75
+ elsif (match = DATE.match(string))
76
+ Date.new(*match.captures.map(&:to_i))
77
+ else
78
+ invalid!("#{field} must be a date (2026-08-01) or a time with an offset (2026-08-01T10:00:00+08:00), " \
79
+ "got #{string.inspect}", provider)
80
+ end
81
+ rescue ArgumentError # Date::Error is one too
82
+ invalid!("#{field} is not a valid date or time, got #{string.inspect}", provider)
83
+ end
84
+
85
+ def invalid!(message, provider)
86
+ raise ValidationError.new(message, provider: provider || "einvoice")
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Einvoice
4
+ # The tax of an invoice or an allowance, computed by the core from its items,
5
+ # +price_mode+, +tax_type+ and +tax_rate+. Adapters read the values their
6
+ # provider wants from here and do not compute tax themselves.
7
+ #
8
+ # The totals are whole TWD and follow the MIG: +sales_amount+ excludes tax and
9
+ # is +taxable_amount+ + +zero_rated_amount+ + +tax_free_amount+, and
10
+ # +total_amount+ is +sales_amount+ + +tax_amount+. A B2C invoice reports its
11
+ # AmountSummary with the tax inside the sales amount (F0401), but its
12
+ # breakdown still splits the tax out, for providers that ask for it.
13
+ TaxBreakdown = Data.define(:lines, :sales_amount, :taxable_amount, :zero_rated_amount, :tax_free_amount,
14
+ :tax_amount, :total_amount)
15
+
16
+ # One line of a TaxBreakdown. +net_amount+ excludes tax, +gross_amount+
17
+ # includes it, and +tax+ is whole TWD. The unit prices come from the item's
18
+ # +unit_price+, rounded to 7 decimal places (MIG 表 15-5). They are not
19
+ # derived from the amounts, so +unit price × quantity+ can differ from the
20
+ # amount by the rounding of the line tax. Each provider note says how much
21
+ # its API allows.
22
+ TaxBreakdown::Line = Data.define(:tax_type, :net_amount, :tax, :gross_amount, :net_unit_price,
23
+ :gross_unit_price)
24
+
25
+ # Splits tax over lines by the largest remainder: each taxed line takes the
26
+ # whole part of its share, and the units left go to the lines with the
27
+ # largest fractions, later lines first on a tie. So the line taxes add up to
28
+ # the total tax, and each line tax is the floor or the ceiling of its share.
29
+ # A line tax has the sign of its amount: a discount line with a negative
30
+ # amount can take a negative tax, and no other line does. Lines that are not
31
+ # taxed have tax 0.
32
+ module TaxSplit
33
+ Line = Data.define(:amount, :tax)
34
+
35
+ module_function
36
+
37
+ # The TaxBreakdown of +items+. An item without a tax_type has the invoice's.
38
+ # With a MIXED invoice tax type, every item needs its own.
39
+ def breakdown(items, tax_type:, tax_rate:, price_mode:, provider: nil)
40
+ types = items.each_with_index.map do |item, index|
41
+ type = item.tax_type || tax_type
42
+ if type.nil? || type == TaxType::MIXED
43
+ invalid!("items[#{index}].tax_type is required when the invoice has mixed tax", provider)
44
+ end
45
+ type
46
+ end
47
+ taxed = types.map { |type| TaxType::TAXED.include?(type) }
48
+ invalid!("tax_rate is required for a #{types.find { |t| TaxType::TAXED.include?(t) }} line", provider) if
49
+ taxed.any? && tax_rate.nil?
50
+
51
+ rate = taxed.any? ? Number.decimal!(tax_rate, field: "tax_rate", provider: provider) : 0r
52
+ # A taxed line at rate 0 would file taxable sales as untaxed.
53
+ invalid!("tax_rate must be above 0 when a line is taxable", provider) if taxed.any? && rate.zero?
54
+ inclusive = price_mode == PriceMode::TAX_INCLUSIVE
55
+ amounts = items.each_with_index.map do |item, index|
56
+ Number.decimal!(item.amount, field: "items[#{index}].amount", provider: provider)
57
+ end
58
+ split = if inclusive
59
+ split(amounts, taxable: taxed, rate: rate)
60
+ else
61
+ allocate(amounts, taxable: taxed, total_tax: (taxable_sum(amounts, taxed) * rate).round)
62
+ end
63
+
64
+ lines = items.each_with_index.map do |item, index|
65
+ price = Number.decimal!(item.unit_price, field: "items[#{index}].unit_price", provider: provider)
66
+ net_price = taxed[index] && inclusive ? price / (1 + rate) : price
67
+ gross_price = taxed[index] && !inclusive ? price * (1 + rate) : price
68
+ line = split[index]
69
+ TaxBreakdown::Line.new(tax_type: types[index], net_amount: Number.plain(line.amount), tax: line.tax,
70
+ gross_amount: Number.plain(line.amount + line.tax),
71
+ net_unit_price: Number.plain(net_price.round(Number::DECIMAL_PLACES)),
72
+ gross_unit_price: Number.plain(gross_price.round(Number::DECIMAL_PLACES)))
73
+ end
74
+ totals(lines, split, inclusive)
75
+ end
76
+
77
+ def totals(lines, split, inclusive)
78
+ tax = split.sum(&:tax)
79
+ sales = inclusive ? split.sum(0r) { |line| line.amount + line.tax }.round - tax : split.sum(0r, &:amount).round
80
+ # Sum the exact split, not the lines: net_amount may be a Float, and 0.35 +
81
+ # 0.15 as Floats rounds to 0, not 1.
82
+ untaxed = lambda do |type|
83
+ lines.zip(split).select { |line, _| line.tax_type == type }.sum(0r) { |_, part| part.amount }.round
84
+ end
85
+ zero = untaxed.call(TaxType::ZERO_RATED)
86
+ free = untaxed.call(TaxType::TAX_FREE)
87
+ TaxBreakdown.new(lines: lines, sales_amount: sales, taxable_amount: sales - zero - free,
88
+ zero_rated_amount: zero, tax_free_amount: free, tax_amount: tax, total_amount: sales + tax)
89
+ end
90
+
91
+ # Splits the tax out of tax-included amounts. The total tax is
92
+ # round(taxed total × rate / (1 + rate)). Returns tax-excluded lines.
93
+ def split(amounts, taxable:, rate:)
94
+ factor = rate / (1 + rate)
95
+ total = (taxable_sum(amounts, taxable) * factor).round
96
+ taxes = distribute(amounts, taxable, total) { |amount| amount * factor }
97
+ amounts.zip(taxes).map { |amount, tax| Line.new(amount: amount - tax, tax: tax) }
98
+ end
99
+
100
+ # Spreads a total tax over tax-excluded amounts, in proportion to the taxed
101
+ # amounts. Returns the lines with their amounts unchanged.
102
+ def allocate(amounts, taxable:, total_tax:)
103
+ base = taxable_sum(amounts, taxable)
104
+ taxes = distribute(amounts, taxable, total_tax) { |amount| base.zero? ? 0 : amount * total_tax / base }
105
+ amounts.zip(taxes).map { |amount, tax| Line.new(amount: amount, tax: tax) }
106
+ end
107
+
108
+ def taxable_sum(amounts, taxable)
109
+ amounts.each_index.sum(0r) { |i| taxable[i] ? amounts[i] : 0 }
110
+ end
111
+
112
+ def distribute(amounts, taxable, total)
113
+ shares = amounts.each_index.map { |i| taxable[i] ? yield(amounts[i]) : 0r }
114
+ taxes = shares.map(&:floor)
115
+ order = amounts.each_index.select { |i| taxable[i] }.sort_by { |i| [taxes[i] - shares[i], -i] }
116
+ (total - taxes.sum).times { |k| taxes[order[k]] += 1 }
117
+ taxes
118
+ end
119
+
120
+ def invalid!(message, provider)
121
+ raise ValidationError.new(message, provider: provider || "einvoice")
122
+ end
123
+ end
124
+ end