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.
Files changed (66) hide show
  1. checksums.yaml +4 -4
  2. data/.coderabbit.yaml +6 -8
  3. data/.github/workflows/build.yml +6 -3
  4. data/.github/workflows/cron.yml +4 -2
  5. data/CHANGELOG.md +63 -44
  6. data/Gemfile +3 -10
  7. data/README.md +284 -325
  8. data/README.zh-TW.md +381 -0
  9. data/Rakefile +2 -51
  10. data/bin/console +3 -6
  11. data/einvoice.gemspec +17 -18
  12. data/lib/einvoice/amego/client.rb +116 -0
  13. data/lib/einvoice/amego/errors.rb +84 -0
  14. data/lib/einvoice/amego/payload.rb +270 -0
  15. data/lib/einvoice/amego/provider.rb +272 -0
  16. data/lib/einvoice/amego.rb +27 -0
  17. data/lib/einvoice/capability.rb +79 -0
  18. data/lib/einvoice/ecpay/client.rb +184 -0
  19. data/lib/einvoice/ecpay/crypto.rb +85 -0
  20. data/lib/einvoice/ecpay/errors.rb +115 -0
  21. data/lib/einvoice/ecpay/payload.rb +241 -0
  22. data/lib/einvoice/ecpay/provider.rb +371 -0
  23. data/lib/einvoice/ecpay.rb +31 -0
  24. data/lib/einvoice/error.rb +220 -0
  25. data/lib/einvoice/ezpay/client.rb +130 -0
  26. data/lib/einvoice/ezpay/crypto.rb +85 -0
  27. data/lib/einvoice/ezpay/errors.rb +72 -0
  28. data/lib/einvoice/ezpay/payload.rb +269 -0
  29. data/lib/einvoice/ezpay/provider.rb +253 -0
  30. data/lib/einvoice/ezpay.rb +19 -0
  31. data/lib/einvoice/input.rb +547 -0
  32. data/lib/einvoice/mock_provider.rb +191 -0
  33. data/lib/einvoice/mof/donation_codes.rb +157 -0
  34. data/lib/einvoice/mof.rb +16 -0
  35. data/lib/einvoice/number.rb +91 -0
  36. data/lib/einvoice/provider.rb +57 -13
  37. data/lib/einvoice/redaction.rb +54 -0
  38. data/lib/einvoice/taipei.rb +89 -0
  39. data/lib/einvoice/tax_split.rb +112 -0
  40. data/lib/einvoice/tradevan/default_api/client.rb +175 -0
  41. data/lib/einvoice/tradevan/default_api/crypto.rb +90 -0
  42. data/lib/einvoice/tradevan/default_api/errors.rb +54 -0
  43. data/lib/einvoice/tradevan/default_api/payload.rb +259 -0
  44. data/lib/einvoice/tradevan/default_api/provider.rb +353 -0
  45. data/lib/einvoice/tradevan/default_api/rules.rb +314 -0
  46. data/lib/einvoice/tradevan.rb +25 -0
  47. data/lib/einvoice/types.rb +365 -0
  48. data/lib/einvoice/version.rb +3 -1
  49. data/lib/einvoice.rb +21 -9
  50. metadata +52 -144
  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 -2025
  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 -139
  63. data/lib/einvoice/tradevan/result.rb +0 -25
  64. data/lib/einvoice/tradevan/validator/issue_data_validator.rb +0 -80
  65. data/lib/faraday/response/decode_tradevan.rb +0 -37
  66. data/lib/faraday/response/parse_xml.rb +0 -14
@@ -0,0 +1,191 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module Einvoice
6
+ # In-memory {Provider} for tests and local development. It runs the same input
7
+ # validation as a real adapter (via {Input}) but never hits the network, so
8
+ # application code can be exercised end-to-end without credentials.
9
+ #
10
+ # It mirrors real-adapter behaviour beyond the happy path: capability gating
11
+ # (each operation, and a non-TWD currency, is refused unless its capability
12
+ # is declared), an in-memory state machine (an invoice with an allowance in
13
+ # force cannot be voided, a voided invoice cannot be credited, and voiding
14
+ # its last allowance returns it to issued), and {#fail_next} to inject a
15
+ # one-shot failure for exercising error handling.
16
+ class MockProvider < Provider
17
+ attr_reader :capabilities
18
+
19
+ # @param track [String] the 字軌 prefix (2 letters) for generated numbers
20
+ # @param seq [Integer] deterministic start for generated invoice numbers
21
+ # @param capabilities [Enumerable] restrict declared capabilities to simulate
22
+ # a specific provider profile; defaults to all
23
+ def initialize(track: "MK", seq: 10_000_000, capabilities: Capability::ALL)
24
+ super()
25
+ @track = track
26
+ @seq = seq
27
+ @allowance_seq = 0
28
+ @capabilities = Set.new(capabilities)
29
+ @invoices = {}
30
+ @by_order_id = {}
31
+ # 折讓單號 => { invoice_number:, voided: }
32
+ @allowances = {}
33
+ @queued_failure = nil
34
+ end
35
+
36
+ def name
37
+ "mock"
38
+ end
39
+
40
+ # Make the next operation raise +error+, then clear it — for exercising a
41
+ # caller's handling of transport/provider failures the happy path never
42
+ # produces (NETWORK, AUTH, NUMBER_EXHAUSTED, …).
43
+ def fail_next(error)
44
+ @queued_failure = error
45
+ end
46
+
47
+ def issue(input)
48
+ check_failure!
49
+ assert_supports!(Capability::ISSUE)
50
+ parsed = Input.issue(input, provider: name)
51
+ assert_currency_supported!(parsed.currency)
52
+ assert_supports!(Capability::B2B) if parsed.resolved_category == InvoiceCategory::B2B
53
+ tax_type = parsed.resolved_tax_type
54
+ assert_supports!(Capability::MIXED_TAX) if tax_type == TaxType::MIXED
55
+ fail!(ConflictError, "Order id already issued", Reason::DUPLICATE_ORDER) if @by_order_id.key?(parsed.order_id)
56
+
57
+ invoice_number = next_invoice_number
58
+ result = IssueInvoiceResult.new(
59
+ invoice_number: invoice_number,
60
+ invoice_datetime: Taipei.now,
61
+ random_code: format("%04d", (@seq * 7) % 10_000),
62
+ order_id: parsed.order_id,
63
+ total_amount: parsed.amount.total_amount,
64
+ buyer_ubn: parsed.buyer&.ubn,
65
+ tax_type: tax_type,
66
+ tax_rate: parsed.tax_rate,
67
+ status: InvoiceStatus::ISSUED,
68
+ raw: { mock: true }
69
+ )
70
+ @invoices[invoice_number] = { input: parsed, result: result, status: InvoiceStatus::ISSUED }
71
+ @by_order_id[parsed.order_id] = invoice_number
72
+ result
73
+ end
74
+
75
+ def void(input)
76
+ check_failure!
77
+ assert_supports!(Capability::VOID)
78
+ parsed = Input.void(input, provider: name)
79
+ stored = require_invoice(parsed.invoice.number)
80
+ fail!(ConflictError, "Invoice already voided", Reason::ALREADY_VOIDED) if
81
+ stored[:status] == InvoiceStatus::VOIDED
82
+ fail!(ConflictError, "Void the invoice's allowances first", Reason::VOID_BLOCKED_BY_ALLOWANCE) if
83
+ allowance_in_force?(parsed.invoice.number)
84
+
85
+ stored[:status] = InvoiceStatus::VOIDED
86
+ VoidInvoiceResult.new(invoice_number: parsed.invoice.number, status: InvoiceStatus::VOIDED,
87
+ cancel_datetime: Taipei.now, raw: { mock: true })
88
+ end
89
+
90
+ def allowance(input)
91
+ check_failure!
92
+ assert_supports!(Capability::ALLOWANCE)
93
+ parsed = Input.allowance(input, provider: name)
94
+ stored = require_invoice(parsed.invoice.number)
95
+ # A voided invoice has nothing left to credit. Deliberately not
96
+ # ALREADY_VOIDED: that one means "already in the state you asked for, treat
97
+ # as success", which here would record a refund that never happened.
98
+ fail!(ConflictError, "Cannot credit a voided invoice", Reason::ALLOWANCE_BLOCKED_BY_VOID) if
99
+ stored[:status] == InvoiceStatus::VOIDED
100
+
101
+ stored[:status] = InvoiceStatus::ALLOWANCE
102
+ @allowance_seq += 1
103
+ allowance_number = format("AL%08d", @allowance_seq)
104
+ @allowances[allowance_number] = { invoice_number: parsed.invoice.number, voided: false }
105
+ AllowanceResult.new(
106
+ allowance_number: allowance_number,
107
+ invoice_number: parsed.invoice.number,
108
+ allowance_date: Taipei.today,
109
+ total_amount: parsed.amount.total_amount,
110
+ raw: { mock: true }
111
+ )
112
+ end
113
+
114
+ def void_allowance(input)
115
+ check_failure!
116
+ assert_supports!(Capability::VOID_ALLOWANCE)
117
+ parsed = Input.void_allowance(input, provider: name)
118
+ allowance_number = parsed.allowance.allowance_number
119
+ allowance = @allowances[allowance_number] || fail!(NotFoundError, "Allowance not found")
120
+ fail!(ConflictError, "Allowance already voided", Reason::ALREADY_VOIDED) if allowance[:voided]
121
+
122
+ allowance[:voided] = true
123
+ invoice_number = allowance[:invoice_number]
124
+ @invoices[invoice_number][:status] = InvoiceStatus::ISSUED unless allowance_in_force?(invoice_number)
125
+ VoidAllowanceResult.new(allowance_number: allowance_number, cancel_datetime: Taipei.now,
126
+ raw: { mock: true })
127
+ end
128
+
129
+ def query(input)
130
+ check_failure!
131
+ assert_supports!(Capability::QUERY)
132
+ parsed = Input.query(input, provider: name)
133
+ reference = parsed.invoice
134
+ assert_supports!(Capability::QUERY_BY_ORDER_ID) if reference.number.nil?
135
+ invoice_number = reference.number || @by_order_id[reference.order_id]
136
+ stored = invoice_number && @invoices[invoice_number]
137
+ fail!(NotFoundError, "Invoice not found") unless stored
138
+
139
+ QueryInvoiceResult.new(
140
+ invoice_number: invoice_number,
141
+ invoice_datetime: stored[:result].invoice_datetime,
142
+ random_code: stored[:result].random_code,
143
+ order_id: stored[:input].order_id,
144
+ status: stored[:status],
145
+ amount: stored[:input].amount,
146
+ buyer: stored[:input].buyer,
147
+ items: stored[:input].items,
148
+ tax_type: stored[:result].tax_type,
149
+ tax_rate: stored[:result].tax_rate,
150
+ raw: { mock: true }
151
+ )
152
+ end
153
+
154
+ # Every well-formed carrier counts as registered.
155
+ def validate_carrier(carrier)
156
+ check_failure!
157
+ assert_supports!(Capability::CARRIER_VALIDATION)
158
+ Input.carrier(carrier, provider: name)
159
+ true
160
+ end
161
+
162
+ private
163
+
164
+ def check_failure!
165
+ return unless @queued_failure
166
+
167
+ error = @queued_failure
168
+ @queued_failure = nil
169
+ raise error
170
+ end
171
+
172
+ def next_invoice_number
173
+ n = @seq
174
+ @seq += 1
175
+ format("%s%08d", @track, n)
176
+ end
177
+
178
+ def allowance_in_force?(invoice_number)
179
+ @allowances.each_value.any? { |a| a[:invoice_number] == invoice_number && !a[:voided] }
180
+ end
181
+
182
+ def require_invoice(invoice_number)
183
+ @invoices[invoice_number] || fail!(NotFoundError, "Invoice not found")
184
+ end
185
+
186
+ # One raise site shape, so a missing reason is visible rather than incidental.
187
+ def fail!(error_class, message, reason = nil)
188
+ raise error_class.new(message, provider: name, reason: reason)
189
+ end
190
+ end
191
+ end
@@ -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,91 @@
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
+ # The default of +if_missing+: the value is required.
10
+ REQUIRED = Object.new.freeze
11
+ private_constant :REQUIRED
12
+
13
+ module_function
14
+
15
+ # A Rational for a number with at most 7 decimal places. Accepts Integer,
16
+ # Rational, BigDecimal, Float and numeric strings. Float goes through its
17
+ # string form, so 0.1 stays 1/10 and does not become a binary fraction.
18
+ def decimal!(value, field:, provider: nil)
19
+ rational = to_rational(value)
20
+ invalid!("#{field} must be a number, got #{value.inspect}", provider) if rational.nil?
21
+ if (rational * (10**DECIMAL_PLACES)).denominator != 1
22
+ invalid!("#{field} may have at most #{DECIMAL_PLACES} decimal places, got #{value.inspect}", provider)
23
+ end
24
+ rational
25
+ end
26
+
27
+ def integer!(value, field:, provider: nil)
28
+ rational = to_rational(value)
29
+ if rational.nil? || rational.denominator != 1
30
+ invalid!("#{field} must be a whole number, got #{value.inspect}", provider)
31
+ end
32
+ rational.to_i
33
+ end
34
+
35
+ def to_rational(value)
36
+ case value
37
+ when Integer, Rational then value.to_r
38
+ when Float then value.finite? ? Rational(value.to_s) : nil
39
+ when Numeric then value.to_r
40
+ when String then value.strip.match?(DECIMAL) ? Rational(value.strip) : nil
41
+ end
42
+ end
43
+
44
+ # An Integer when the value is whole, else a Float, so an amount serializes
45
+ # as 95 or 47.5 and not as a Rational.
46
+ def plain(value)
47
+ value.denominator == 1 ? value.to_i : value.to_f
48
+ end
49
+
50
+ # --- provider responses ----------------------------------------------------
51
+ #
52
+ # A number in a provider's response goes through the same parser as the
53
+ # input. It is the provider's data, not the caller's, so a value that is not
54
+ # a number raises ProviderError, with the response in +raw+. Nothing reads
55
+ # such a value as 0, and nothing cuts off its decimals.
56
+
57
+ # A Rational, or nil when the provider sent no value.
58
+ def response(value, field:, provider:, raw:)
59
+ return nil if value.nil? || (value.is_a?(String) && value.strip.empty?)
60
+
61
+ rational = to_rational(value)
62
+ return rational unless rational.nil?
63
+
64
+ raise ProviderError.new("the #{provider} response has a #{field} that is not a number: #{value.inspect}",
65
+ provider: provider, raw: raw)
66
+ end
67
+
68
+ # #response as an Integer or a Float (#plain), or nil when it is missing.
69
+ # For the numbers of an item, which may have decimals.
70
+ def response_plain(value, field:, provider:, raw:)
71
+ rational = response(value, field: field, provider: provider, raw: raw)
72
+ rational && plain(rational)
73
+ end
74
+
75
+ # A whole number, such as a total. The provider has to send it, unless
76
+ # +if_missing+ gives the value to use when it does not. Use that only for a
77
+ # field that no live response shows, and say why where it is used.
78
+ def response_integer!(value, field:, provider:, raw:, if_missing: REQUIRED)
79
+ rational = response(value, field: field, provider: provider, raw: raw)
80
+ return if_missing if rational.nil? && !REQUIRED.equal?(if_missing)
81
+ return rational.to_i if rational&.denominator == 1
82
+
83
+ problem = rational.nil? ? "has no #{field}" : "has a #{field} that is not a whole number: #{value.inspect}"
84
+ raise ProviderError.new("the #{provider} response #{problem}", provider: provider, raw: raw)
85
+ end
86
+
87
+ def invalid!(message, provider)
88
+ raise ValidationError.new(message, provider: provider || "einvoice")
89
+ end
90
+ end
91
+ end
@@ -1,22 +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)
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
4
29
 
5
- def initialize(options={})
6
- options = Einvoice.options.merge(options)
7
- Configuration::VALID_OPTIONS_KEYS.each do |key|
8
- send("#{key}=", options[key])
9
- end
30
+ # 作廢發票.
31
+ def void(_input)
32
+ raise NotImplementedError, "#{self.class} must implement #void"
10
33
  end
11
34
 
12
- def config
13
- conf = {}
14
- Configuration::VALID_OPTIONS_KEYS.each do |key|
15
- conf[key] = send key
16
- end
17
- conf
35
+ # 開立折讓.
36
+ def allowance(_input)
37
+ raise NotImplementedError, "#{self.class} must implement #allowance"
18
38
  end
19
39
 
20
- 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
21
65
  end
22
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