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,547 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Einvoice
4
+ # Coerces a plain Hash (symbol- or string-keyed — e.g. a JSON fixture) into the
5
+ # immutable value types, validating as it goes and raising
6
+ # {ValidationError} on bad input. Adapters call these before mapping to their
7
+ # wire format, so a malformed request fails the same way everywhere and never
8
+ # reaches the network.
9
+ #
10
+ # A value object built with +.new+ goes through the same checks as a Hash:
11
+ # Input turns it back into a Hash first. So whatever an adapter gets from
12
+ # Input has passed every check, however the caller built it.
13
+ #
14
+ # Enum fields accept either the canonical symbol (+:taxable+) or a wire-style
15
+ # string (+"TAXABLE"+, any case) — the bridge that lets the Ruby SDK consume
16
+ # the same language-neutral fixtures as the TypeScript one.
17
+ #
18
+ # Deliberately dependency-free: a small hand-written validator, not a schema
19
+ # library, keeping the core's runtime dependencies at zero.
20
+ module Input
21
+ # 統一編號 [mig 表 4-7].
22
+ UBN_FORMAT = /\A\d{8}\z/
23
+ # 手機條碼: "/" and 7 of 0-9 A-Z . + -. 自然人憑證: 2 letters and 14 digits.
24
+ CARRIER_FORMATS = {
25
+ CarrierType::MOBILE_BARCODE => %r{\A/[0-9A-Z.+-]{7}\z},
26
+ CarrierType::CITIZEN_CERTIFICATE => /\A[A-Z]{2}\d{14}\z/
27
+ }.freeze
28
+ # MIG F0501 and G0501 allow a reason of 1 to 20 characters.
29
+ MAX_REASON_LENGTH = 20
30
+ # MIG 4.1 field lengths, checked here once so that every provider gets the
31
+ # same answer [mig 表 4-2, 15-2, 15-5, 18-2]. A shorter limit of one
32
+ # provider is that adapter's UnsupportedError.
33
+ MIG_LENGTHS = {
34
+ remark: 200, buyer_name: 60, buyer_address: 100, buyer_email: 400, buyer_phone: 26,
35
+ carrier_code: 400, item_description: 500, item_unit: 6, item_remark: 120
36
+ }.freeze
37
+ # MIG 表 4-2: a consumer's name must not be 0 to 0000.
38
+ ZERO_NAME = /\A0{1,4}\z/
39
+ # MIG CustomsClearanceMarkEnum and ZeroTaxRateReasonEnum [mig 表 4-9, 4-19].
40
+ CUSTOMS_CLEARANCE_MARKS = %w[1 2].freeze
41
+ ZERO_TAX_RATE_REASONS = ("71".."79").to_a.freeze
42
+ DEFAULT_VOID_ALLOWANCE_REASON = "作廢折讓"
43
+ # The rates the MIG allows [mig 表 4-18].
44
+ TAX_RATES = [0, Rational(1, 100), Rational(2, 100), Rational(5, 100), Rational(15, 100),
45
+ Rational(25, 100)].freeze
46
+ # The general rate (一般稅額) is 5% to 10% [營業稅法第 10 條], and 0.05 is
47
+ # the only MIG rate in that range. The other MIG rates are for special tax
48
+ # (特種稅額) [第 11 至 13 條]. If the general rate changes, change it here.
49
+ # Each adapter keeps its own check, because a provider may stay at 5%.
50
+ TAXABLE_RATES = [Rational(5, 100)].freeze
51
+ STANDARD_TAX_RATE = TAXABLE_RATES.first
52
+ # A reference or an allowance can describe a mixed-tax invoice.
53
+ REFERENCE_TAX_TYPES = (TaxType::ALL + [TaxType::MIXED]).freeze
54
+
55
+ module_function
56
+
57
+ def issue(input, provider: nil)
58
+ h = hash!(unbuild(input), "input", provider)
59
+ items = build_items(h[:items], provider)
60
+ amount = build_amount(h[:amount], provider)
61
+ buyer = build_buyer(h[:buyer], provider)
62
+ tax_type = enum!(h[:tax_type], TaxType::ALL, :tax_type, provider)
63
+ category = h[:category] && enum!(h[:category], InvoiceCategory::ALL, :category, provider)
64
+ check_category!(category, buyer, provider)
65
+ check_consumer_name!(category, buyer, provider)
66
+ tax_rate = tax_rate!(h[:tax_rate], items, tax_type, provider)
67
+ check_tax_rate!(tax_rate, items, tax_type, provider)
68
+ parsed = IssueInvoiceInput.new(
69
+ order_id: fetch!(h, :order_id, provider),
70
+ buyer: buyer,
71
+ items: items,
72
+ amount: amount,
73
+ tax_type: tax_type,
74
+ price_mode: enum!(h[:price_mode], PriceMode::ALL, :price_mode, provider),
75
+ tax_rate: tax_rate,
76
+ category: category,
77
+ carrier: build_carrier(h[:carrier], provider),
78
+ donation: build_donation(h[:donation], provider),
79
+ remark: length!(h[:remark], :remark, provider),
80
+ currency: h[:currency],
81
+ exchange_rate: h[:exchange_rate],
82
+ customs_clearance_mark: code!(h[:customs_clearance_mark], CUSTOMS_CLEARANCE_MARKS,
83
+ :customs_clearance_mark, provider),
84
+ zero_tax_rate_reason: code!(h[:zero_tax_rate_reason], ZERO_TAX_RATE_REASONS,
85
+ :zero_tax_rate_reason, provider),
86
+ provider_options: h[:provider_options]
87
+ )
88
+ if parsed.amount.nil?
89
+ parsed = parsed.with(amount: issue_amount(parsed, provider))
90
+ else
91
+ check_issue_amount!(parsed, provider)
92
+ end
93
+ check_zero_rated!(parsed, provider)
94
+ parsed
95
+ end
96
+
97
+ def void(input, provider: nil)
98
+ h = hash!(unbuild(input), "input", provider)
99
+ VoidInvoiceInput.new(
100
+ invoice: invoice_reference!(h[:invoice], provider, need_number: true),
101
+ reason: reason!(fetch!(h, :reason, provider), provider),
102
+ provider_options: h[:provider_options]
103
+ )
104
+ end
105
+
106
+ # The tax type and rate come from the input, else from the invoice
107
+ # reference. There is no default: an allowance taxed at the wrong rate is a
108
+ # wrong filing. An allowance with no taxed line has rate 0.
109
+ def allowance(input, provider: nil)
110
+ h = hash!(unbuild(input), "input", provider)
111
+ invoice = invoice_reference!(h[:invoice], provider, need_number: true)
112
+ tax_type = h[:tax_type] ? enum!(h[:tax_type], REFERENCE_TAX_TYPES, :tax_type, provider) : invoice.tax_type
113
+ fail!("tax_type is required, or invoice.tax_type in the reference", provider) if tax_type.nil?
114
+
115
+ items = build_items(h[:items], provider)
116
+ check_item_tax_types!(items, tax_type, provider)
117
+ check_not_negative!(items, provider)
118
+ check_whole_amounts!(items, provider)
119
+ tax_rate = h[:tax_rate].nil? ? invoice.tax_rate : mig_rate!(h[:tax_rate], "tax_rate", provider)
120
+ tax_rate ||= 0r if TaxType.per_item(items, tax_type).none? { |type| TaxType::TAXED.include?(type) }
121
+ fail!("tax_rate is required, or invoice.tax_rate in the reference", provider) if tax_rate.nil?
122
+ check_tax_rate!(tax_rate, items, tax_type, provider)
123
+
124
+ parsed = AllowanceInput.new(
125
+ invoice: invoice,
126
+ allowance_id: fetch!(h, :allowance_id, provider),
127
+ items: items,
128
+ amount: build_amount(h[:amount], provider),
129
+ price_mode: enum!(h[:price_mode], PriceMode::ALL, :price_mode, provider),
130
+ tax_type: tax_type,
131
+ tax_rate: tax_rate,
132
+ provider_options: h[:provider_options]
133
+ )
134
+ if parsed.amount.nil?
135
+ parsed = parsed.with(amount: allowance_amount(parsed, provider))
136
+ else
137
+ check_allowance_amount!(parsed, provider)
138
+ end
139
+ parsed
140
+ end
141
+
142
+ def void_allowance(input, provider: nil)
143
+ h = hash!(unbuild(input), "input", provider)
144
+ VoidAllowanceInput.new(
145
+ allowance: allowance_reference!(h[:allowance], provider),
146
+ reason: reason!(blank?(h[:reason]) ? DEFAULT_VOID_ALLOWANCE_REASON : h[:reason], provider),
147
+ provider_options: h[:provider_options]
148
+ )
149
+ end
150
+
151
+ def query(input, provider: nil)
152
+ h = hash!(unbuild(input), "input", provider)
153
+ invoice = invoice_reference!(h[:invoice], provider, need_number: false)
154
+ if blank?(invoice.number) && blank?(invoice.order_id)
155
+ fail!("query needs invoice.number or invoice.order_id", provider)
156
+ end
157
+ QueryInvoiceInput.new(invoice: invoice, provider_options: h[:provider_options])
158
+ end
159
+
160
+ # A carrier on its own, for Provider#validate_carrier.
161
+ def carrier(input, provider: nil)
162
+ fail!("carrier is required", provider) if input.nil?
163
+
164
+ build_carrier(unbuild(input), provider)
165
+ end
166
+
167
+ # A value object back to the Hash it came from, all the way down, so it
168
+ # takes the same path through the checks as a Hash. A reference becomes
169
+ # its stored form (#to_h).
170
+ def unbuild(value)
171
+ case value
172
+ when InvoiceReference, AllowanceReference then value.to_h
173
+ when Data then value.to_h.transform_values { |field| unbuild(field) }
174
+ when Hash then value.transform_values { |field| unbuild(field) }
175
+ when Array then value.map { |item| unbuild(item) }
176
+ else value
177
+ end
178
+ end
179
+
180
+ # --- amounts ---------------------------------------------------------------
181
+
182
+ # The items decide the totals. An invoice follows F0401: for a consumer the
183
+ # tax is inside sales_amount and tax_amount is 0, for a business it is apart.
184
+ # Either way the tax is round(taxable sales × tax_rate), so the same input
185
+ # gets the same tax at every provider.
186
+ def check_issue_amount!(input, provider)
187
+ breakdown = input.tax_breakdown
188
+ amount = input.amount
189
+ check_total!(amount, breakdown, provider)
190
+ if input.resolved_category == InvoiceCategory::B2B
191
+ check_tax!(amount, breakdown, input.tax_rate, provider)
192
+ elsif !amount.tax_amount.zero?
193
+ fail!("a B2C invoice has tax_amount 0 and the tax inside sales_amount (F0401), got tax_amount " \
194
+ "#{amount.tax_amount}", provider)
195
+ end
196
+ end
197
+
198
+ # The totals that the core derives when the caller gives no +amount+, by
199
+ # the same rules that check a given one: F0401 for an invoice, G0401 for an
200
+ # allowance.
201
+ def issue_amount(input, provider)
202
+ breakdown = input.tax_breakdown
203
+ total = breakdown.total_amount
204
+ tax = input.resolved_category == InvoiceCategory::B2B ? breakdown.tax_amount : 0
205
+ totals = { sales_amount: total - tax, tax_amount: tax, total_amount: total }
206
+ # Discount lines can take the items below zero. A given amount cannot be
207
+ # negative, so a derived one cannot be either.
208
+ totals.each do |field, value|
209
+ fail!("amount.#{field} must not be negative, got #{value}", provider) if value.negative?
210
+ end
211
+ AmountSummary.new(**totals)
212
+ end
213
+
214
+ def allowance_amount(input, provider)
215
+ breakdown = input.tax_breakdown
216
+ AmountSummary.new(sales_amount: breakdown.total_amount - breakdown.tax_amount,
217
+ tax_amount: breakdown.tax_amount, total_amount: breakdown.total_amount)
218
+ end
219
+
220
+ # An allowance follows G0401: sales_amount excludes tax.
221
+ def check_allowance_amount!(input, provider)
222
+ breakdown = input.tax_breakdown
223
+ check_total!(input.amount, breakdown, provider)
224
+ check_tax!(input.amount, breakdown, input.tax_rate, provider)
225
+ end
226
+
227
+ def check_total!(amount, breakdown, provider)
228
+ return if amount.total_amount == breakdown.total_amount
229
+
230
+ fail!("total_amount is #{amount.total_amount}, but the items add up to #{breakdown.total_amount} " \
231
+ "with tax", provider)
232
+ end
233
+
234
+ def check_tax!(amount, breakdown, rate, provider)
235
+ return if amount.tax_amount == breakdown.tax_amount
236
+
237
+ fail!("tax_amount is #{amount.tax_amount}, but the tax of the items is #{breakdown.tax_amount} " \
238
+ "(taxable #{breakdown.taxable_amount} at #{Number.plain(rate.to_r)})", provider)
239
+ end
240
+
241
+ # --- references ------------------------------------------------------------
242
+
243
+ # An InvoiceReference, a Hash of its fields, or a plain invoice number.
244
+ def invoice_reference!(value, provider, need_number:)
245
+ fail!("invoice is required", provider) if blank?(value)
246
+
247
+ reference = if value.is_a?(String)
248
+ InvoiceReference.new(number: value)
249
+ else
250
+ build_invoice_reference(hash!(value, "invoice", provider), provider)
251
+ end
252
+ fail!("invoice.number is required", provider) if need_number && blank?(reference.number)
253
+ reference
254
+ end
255
+
256
+ def build_invoice_reference(h, provider)
257
+ ubn = blank?(h[:buyer_ubn]) ? nil : h[:buyer_ubn].to_s
258
+ fail!("invoice.buyer_ubn must be 8 digits, got #{ubn.inspect}", provider) if ubn && !ubn.match?(UBN_FORMAT)
259
+
260
+ InvoiceReference.new(
261
+ number: presence(h[:number]),
262
+ invoice_datetime: h[:invoice_datetime] &&
263
+ Taipei.time(h[:invoice_datetime], field: "invoice.invoice_datetime", provider: provider),
264
+ random_code: presence(h[:random_code]),
265
+ order_id: presence(h[:order_id]),
266
+ total_amount: h[:total_amount] && Number.integer!(h[:total_amount], field: "invoice.total_amount",
267
+ provider: provider),
268
+ buyer_ubn: ubn,
269
+ tax_type: h[:tax_type] && enum!(h[:tax_type], REFERENCE_TAX_TYPES, :"invoice.tax_type", provider),
270
+ tax_rate: h[:tax_rate].nil? ? nil : mig_rate!(h[:tax_rate], "invoice.tax_rate", provider)
271
+ )
272
+ end
273
+
274
+ # An AllowanceReference, a Hash of its fields, or a plain allowance number.
275
+ def allowance_reference!(value, provider)
276
+ fail!("allowance is required", provider) if blank?(value)
277
+ return AllowanceReference.new(allowance_number: value) if value.is_a?(String)
278
+
279
+ h = hash!(value, "allowance", provider)
280
+ AllowanceReference.new(
281
+ allowance_number: fetch!(h, :allowance_number, provider),
282
+ allowance_date: h[:allowance_date] &&
283
+ Taipei.date(h[:allowance_date], field: "allowance.allowance_date", provider: provider),
284
+ invoice_number: presence(h[:invoice_number])
285
+ )
286
+ end
287
+
288
+ def presence(value)
289
+ blank?(value) ? nil : value
290
+ end
291
+
292
+ # --- builders --------------------------------------------------------------
293
+
294
+ def build_buyer(value, provider)
295
+ return nil if value.nil?
296
+
297
+ h = hash!(value, "buyer", provider)
298
+ ubn = blank?(h[:ubn]) ? nil : h[:ubn].to_s
299
+ fail!("buyer ubn must be 8 digits, got #{ubn.inspect}", provider) if ubn && !ubn.match?(UBN_FORMAT)
300
+
301
+ Buyer.new(name: length!(h[:name], :buyer_name, provider), ubn: ubn,
302
+ email: length!(h[:email], :buyer_email, provider),
303
+ address: length!(h[:address], :buyer_address, provider),
304
+ phone: length!(h[:phone], :buyer_phone, provider))
305
+ end
306
+
307
+ def build_carrier(value, provider)
308
+ return nil if value.nil?
309
+
310
+ h = hash!(value, "carrier", provider)
311
+ type = enum!(h[:type], CarrierType::ALL, :carrier_type, provider)
312
+ format = CARRIER_FORMATS[type]
313
+ if format && !h[:code].to_s.match?(format)
314
+ fail!("carrier code for #{type} must match #{format.source}, got #{h[:code].inspect}", provider)
315
+ end
316
+ # MIG 表 15-3: no space, half-width or full-width, at either end.
317
+ if h[:code].to_s.match?(/\A[\s\u3000]|[\s\u3000]\z/)
318
+ fail!("carrier code must not start or end with a space, got #{h[:code].inspect}", provider)
319
+ end
320
+ Carrier.new(type: type, code: length!(h[:code], :carrier_code, provider))
321
+ end
322
+
323
+ def build_donation(value, provider)
324
+ return nil if value.nil?
325
+
326
+ # Kept as a String: a 愛心碼 is an identifier, not a number, and real ones
327
+ # carry a leading zero (0096) that an integer round-trip would destroy.
328
+ npoban = fetch!(hash!(value, "donation", provider), :npoban, provider).to_s
329
+ unless npoban.match?(Donation::CODE_FORMAT)
330
+ fail!("npoban must be 3–7 digits (愛心碼), got #{npoban.inspect}", provider)
331
+ end
332
+
333
+ Donation.new(npoban: npoban)
334
+ end
335
+
336
+ # nil when the caller gives no amount: the core derives it from the items.
337
+ def build_amount(value, provider)
338
+ return nil if value.nil?
339
+
340
+ h = hash!(value, "amount", provider)
341
+ sales, tax, total = %i[sales_amount tax_amount total_amount].map do |field|
342
+ value = Number.integer!(h[field], field: "amount.#{field}", provider: provider)
343
+ fail!("amount.#{field} must not be negative, got #{value}", provider) if value.negative?
344
+ value
345
+ end
346
+ unless sales + tax == total
347
+ fail!("amount total #{total} != sales #{sales} + tax #{tax}", provider)
348
+ end
349
+ AmountSummary.new(sales_amount: sales, tax_amount: tax, total_amount: total)
350
+ end
351
+
352
+ def build_items(value, provider)
353
+ fail!("items must be a non-empty array", provider) unless value.is_a?(Array) && !value.empty?
354
+
355
+ value.each_with_index.map do |item, index|
356
+ h = hash!(item, "items[#{index}]", provider)
357
+ %i[quantity unit_price amount].each do |field|
358
+ Number.decimal!(fetch!(h, field, provider), field: "items[#{index}].#{field}", provider: provider)
359
+ end
360
+ InvoiceItem.new(
361
+ description: length!(fetch!(h, :description, provider), :item_description, provider),
362
+ quantity: fetch!(h, :quantity, provider),
363
+ unit_price: fetch!(h, :unit_price, provider),
364
+ amount: fetch!(h, :amount, provider),
365
+ unit: length!(h[:unit], :item_unit, provider),
366
+ tax_type: h[:tax_type] && enum!(h[:tax_type], TaxType::ALL, :tax_type, provider),
367
+ remark: length!(h[:remark], :item_remark, provider)
368
+ )
369
+ end
370
+ end
371
+
372
+ # --- checks ----------------------------------------------------------------
373
+
374
+ # Only an allowance can have a MIXED tax type, from the reference of a
375
+ # mixed-tax invoice. MIXED is not a type of a line, so each item then needs
376
+ # its own.
377
+ def check_item_tax_types!(items, tax_type, provider)
378
+ return unless tax_type == TaxType::MIXED
379
+
380
+ index = items.index { |item| item.tax_type.nil? }
381
+ fail!("items[#{index}].tax_type is required when the invoice has mixed tax", provider) if index
382
+ end
383
+
384
+ # G0401 wants each item amount without tax in whole TWD [mig 表 18-5]. A
385
+ # line tax is whole TWD too, so the amount the caller gives has to be whole,
386
+ # with or without tax. Quantity and unit price may still have decimals.
387
+ def check_whole_amounts!(items, provider)
388
+ items.each_with_index do |item, index|
389
+ next if Number.decimal!(item.amount, field: "items[#{index}].amount", provider: provider).denominator == 1
390
+
391
+ fail!("items[#{index}].amount must be a whole number on an allowance (MIG G0401), got #{item.amount}",
392
+ provider)
393
+ end
394
+ end
395
+
396
+ # MIG 4.1 does not allow a negative amount on an allowance. An invoice may
397
+ # have a negative discount line, so build_items does not check this.
398
+ def check_not_negative!(items, provider)
399
+ items.each_with_index do |item, index|
400
+ %i[amount quantity unit_price].each do |field|
401
+ value = Number.decimal!(item.public_send(field), field: "items[#{index}].#{field}", provider: provider)
402
+ fail!("items[#{index}].#{field} must not be negative, got #{item.public_send(field)}", provider) if
403
+ value.negative?
404
+ end
405
+ end
406
+ end
407
+
408
+ # A B2B invoice needs a 統一編號. An explicit category has to agree with it.
409
+ # The value as it is, after a check against its MIG length.
410
+ def length!(value, field, provider)
411
+ limit = MIG_LENGTHS.fetch(field)
412
+ length = value.to_s.length
413
+ fail!("#{field} must be #{limit} characters or fewer (MIG), got #{length}", provider) if length > limit
414
+ value
415
+ end
416
+
417
+ def check_consumer_name!(category, buyer, provider)
418
+ return if buyer.nil? || buyer.business? || category == InvoiceCategory::B2B
419
+ return unless buyer.name.to_s.match?(ZERO_NAME)
420
+
421
+ fail!("a consumer's buyer name must not be #{buyer.name.inspect} (MIG)", provider)
422
+ end
423
+
424
+ def check_category!(category, buyer, provider)
425
+ business = buyer&.business? || false
426
+ if category == InvoiceCategory::B2B && !business
427
+ fail!("a B2B invoice needs buyer.ubn", provider)
428
+ elsif category == InvoiceCategory::B2C && business
429
+ fail!("a B2C invoice cannot carry buyer.ubn #{buyer.ubn}", provider)
430
+ end
431
+ end
432
+
433
+ # A decimal rate that the MIG allows. When none is given, the lines decide,
434
+ # not the header: a taxable line is taxed at 5% under a tax-free header
435
+ # too. A special-tax line has no default: the caller has to give its rate.
436
+ def tax_rate!(value, items, tax_type, provider)
437
+ return mig_rate!(value, "tax_rate", provider) unless value.nil?
438
+
439
+ types = TaxType.per_item(items, tax_type)
440
+ return nil if types.include?(TaxType::SPECIAL)
441
+
442
+ types.include?(TaxType::TAXABLE) ? STANDARD_TAX_RATE : 0r
443
+ end
444
+
445
+ # A taxed line needs a rate above 0. At rate 0 it would file taxable sales
446
+ # as untaxed. A taxable line takes the general rate only. Lines that are
447
+ # not taxed do not use the rate.
448
+ def check_tax_rate!(rate, items, tax_type, provider)
449
+ types = TaxType.per_item(items, tax_type)
450
+ taxed = types.find { |type| TaxType::TAXED.include?(type) }
451
+ return if taxed.nil?
452
+
453
+ fail!("tax_rate is required for a #{taxed} line", provider) if rate.nil?
454
+ fail!("tax_rate must be above 0 when a line is taxable", provider) if rate.zero?
455
+ return unless types.include?(TaxType::TAXABLE) && !TAXABLE_RATES.include?(rate)
456
+
457
+ fail!("a taxable line takes the general rate #{TAXABLE_RATES.map { |r| Number.plain(r) }.join(', ')}, " \
458
+ "got #{Number.plain(rate)}. The other rates are for special tax", provider)
459
+ end
460
+
461
+ def mig_rate!(value, field, provider)
462
+ rate = Number.decimal!(value, field: field, provider: provider)
463
+ unless TAX_RATES.include?(rate)
464
+ fail!("#{field} must be one of the MIG rates (0, 0.01, 0.02, 0.05, 0.15, 0.25), got #{value.inspect}",
465
+ provider)
466
+ end
467
+ rate
468
+ end
469
+
470
+ # A MIG code given as a String or an Integer. nil when it is not given.
471
+ def code!(value, codes, field, provider)
472
+ return nil if blank?(value)
473
+
474
+ code = value.to_s
475
+ fail!("#{field} must be one of #{codes.join(', ')}, got #{value.inspect}", provider) unless codes.include?(code)
476
+ code
477
+ end
478
+
479
+ # The MIG requires CustomsClearanceMark and ZeroTaxRateReason on a
480
+ # zero-rated invoice [mig 表 15-3]. ECPay can take the reason from its back
481
+ # office, but the reason goes to the MOF in the end, so the caller gives it.
482
+ def check_zero_rated!(parsed, provider)
483
+ return unless parsed.zero_rated?
484
+
485
+ if parsed.customs_clearance_mark.nil?
486
+ fail!("a zero-rated invoice needs customs_clearance_mark (1 or 2)", provider)
487
+ end
488
+ return unless parsed.zero_tax_rate_reason.nil?
489
+
490
+ fail!("a zero-rated invoice needs zero_tax_rate_reason (71 to 79)", provider)
491
+ end
492
+
493
+ def reason!(reason, provider)
494
+ length = reason.to_s.length
495
+ fail!("reason must be #{MAX_REASON_LENGTH} characters or fewer, got #{length}", provider) if length > MAX_REASON_LENGTH
496
+ reason
497
+ end
498
+
499
+ # --- helpers ---------------------------------------------------------------
500
+
501
+ def enum!(value, allowed, field, provider)
502
+ return value if allowed.include?(value)
503
+
504
+ symbol = value.is_a?(String) ? value.downcase.to_sym : nil
505
+ return symbol if symbol && allowed.include?(symbol)
506
+
507
+ fail!("invalid #{field}: #{value.inspect}", provider)
508
+ end
509
+
510
+ # Read a required field, or fail naming it. "Required" means present, not
511
+ # merely non-nil: an empty string is a missing value everywhere in this
512
+ # model, and letting one through only defers the failure to the provider.
513
+ def fetch!(hash, key, provider)
514
+ value = hash[key]
515
+ fail!("#{key} is required", provider) if blank?(value)
516
+ value
517
+ end
518
+
519
+ def blank?(value)
520
+ value.nil? || (value.respond_to?(:empty?) && value.empty?)
521
+ end
522
+
523
+ def fail!(message, provider)
524
+ raise ValidationError.new(message, provider: provider || "einvoice")
525
+ end
526
+
527
+ # Coerce a value that has to be an object, naming the field it came from.
528
+ # Every nested shape goes through here, so a caller who passes a String, an
529
+ # Array or nothing at all gets the same {ValidationError} as any other bad
530
+ # input instead of a NoMethodError raised three frames deeper.
531
+ def hash!(value, field, provider)
532
+ fail!("#{field} must be an object, got #{type_of(value)}", provider) unless value.is_a?(Hash)
533
+
534
+ symbolize_keys(value)
535
+ end
536
+
537
+ # One level deep, which is all the nesting there is: arrays of hashes are
538
+ # handled by the per-item builders, which call back through {hash!}.
539
+ def symbolize_keys(hash)
540
+ hash.each_with_object({}) { |(key, value), out| out[key.to_sym] = value }
541
+ end
542
+
543
+ def type_of(value)
544
+ value.nil? ? "nil" : value.class.name
545
+ end
546
+ end
547
+ end