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,84 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Einvoice
4
+ module Amego
5
+ # Maps Amego's +code+ values onto the unified {Einvoice::Error} tree.
6
+ #
7
+ # The codes come from Amego's error code page
8
+ # (https://invoice.amego.tw/info_detail?mid=71). docs/providers/amego/api.md
9
+ # section 6.4 lists them. Codes +15+ and +71+ were seen on the live test
10
+ # account.
11
+ module Errors
12
+ # code => [error class code, Reason or nil]
13
+ CODES = {
14
+ # Common codes.
15
+ 10 => [:provider, nil], # system maintenance
16
+ 11 => [:auth, Reason::CREDENTIALS_INVALID], # invoice (統一編號) empty
17
+ 12 => [:auth, Reason::CREDENTIALS_INVALID], # invoice (統一編號) wrong
18
+ 13 => [:auth, Reason::NOT_ENROLLED], # status not active
19
+ 14 => [:auth, Reason::IP_BLOCKED],
20
+ 15 => [:auth, Reason::STALE_TIMESTAMP], # time out of range
21
+ 16 => [:auth, Reason::CREDENTIALS_INVALID], # sign wrong
22
+ 17 => [:validation, nil], # data empty
23
+ 18 => [:provider, nil], # database connection failed
24
+ 19 => [:auth, Reason::ACCOUNT_SUSPENDED],
25
+ 20 => [:validation, nil], # data is not JSON
26
+ 21 => [:provider, Reason::RATE_LIMITED],
27
+ 22 => [:auth, Reason::NOT_ENROLLED], # API access not applied for
28
+ 23 => [:validation, nil], # this API takes an array
29
+ 51 => [:provider, nil], # past the 180-day query limit
30
+ 71 => [:not_found, nil],
31
+ 99 => [:provider, nil],
32
+ # f0401
33
+ 3_040_111 => [:number_exhausted, nil],
34
+ 3_040_132 => [:validation, Reason::CARRIER_NOT_REGISTERED],
35
+ 3_040_171 => [:conflict, Reason::DUPLICATE_ORDER],
36
+ 3_040_191 => [:number_exhausted, nil],
37
+ # f0501
38
+ 3_050_111 => [:validation, nil],
39
+ 3_050_113 => [:validation, nil],
40
+ 3_050_121 => [:conflict, Reason::RETRY_LATER], # still being issued
41
+ 3_050_122 => [:conflict, Reason::ALREADY_VOIDED],
42
+ 3_050_123 => [:conflict, nil], # already cancelled (註銷)
43
+ 3_050_125 => [:not_found, nil],
44
+ 3_050_126 => [:conflict, Reason::PAST_DEADLINE],
45
+ 3_050_131 => [:conflict, Reason::RETRY_LATER], # a queued change is waiting
46
+ 3_050_141 => [:conflict, Reason::VOID_BLOCKED_BY_ALLOWANCE],
47
+ # g0401
48
+ 4_040_145 => [:validation, nil],
49
+ 4_040_151 => [:validation, nil],
50
+ 4_040_153 => [:conflict, Reason::ALLOWANCE_BLOCKED_BY_VOID],
51
+ 4_040_154 => [:conflict, nil], # original invoice cancelled
52
+ 4_040_156 => [:not_found, nil],
53
+ 4_040_157 => [:validation, nil],
54
+ 4_040_161 => [:conflict, Reason::DUPLICATE_ALLOWANCE],
55
+ 4_040_171 => [:validation, nil],
56
+ 4_040_173 => [:validation, nil],
57
+ # g0501
58
+ 4_050_132 => [:conflict, Reason::ALREADY_VOIDED],
59
+ 4_050_134 => [:not_found, nil],
60
+ 4_050_135 => [:conflict, Reason::PAST_DEADLINE],
61
+ 4_050_141 => [:conflict, Reason::RETRY_LATER], # a queued change is waiting
62
+
63
+ 9_000_111 => [:validation, nil], # barcode empty
64
+ 9_000_112 => [:validation, nil] # barcode format wrong
65
+ }.freeze
66
+
67
+ # The other f0401 codes from 3040101 to 3040199 are field format errors.
68
+ ISSUE_FIELD_ERRORS = (3_040_101..3_040_199)
69
+
70
+ module_function
71
+
72
+ # @return [Array(Symbol, Symbol)] the error class code and the Reason
73
+ # (or nil). Codes outside the table are +:provider+: Amego knows why it
74
+ # refused, and we do not.
75
+ def classify(code)
76
+ code = Integer(code, exception: false)
77
+ return CODES[code] if CODES.key?(code)
78
+ return [:validation, nil] if code && ISSUE_FIELD_ERRORS.cover?(code)
79
+
80
+ [:provider, nil]
81
+ end
82
+ end
83
+ end
84
+ end
@@ -0,0 +1,270 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module Einvoice
6
+ module Amego
7
+ # Maps the unified value model onto Amego's JSON payloads, and checks the
8
+ # rules from docs/providers/amego/api.md locally, so a bad request fails
9
+ # before the network. The core has already checked the input and computed
10
+ # the tax, so this module only translates.
11
+ module Payload
12
+ # 課稅別 → Amego TaxType. 9 (混合) is derived from the items.
13
+ TAX_TYPE = {
14
+ TaxType::TAXABLE => "1",
15
+ TaxType::ZERO_RATED => "2",
16
+ TaxType::TAX_FREE => "3"
17
+ }.freeze
18
+ MIXED_TAX_CODE = "9"
19
+
20
+ CARRIER_TYPE = {
21
+ CarrierType::MOBILE_BARCODE => "3J0002",
22
+ CarrierType::CITIZEN_CERTIFICATE => "CQ0001",
23
+ CarrierType::MEMBER => "amego" # Amego's own member carrier
24
+ }.freeze
25
+
26
+ CONSUMER_ID = "0000000000"
27
+ CONSUMER_NAME = "消費者"
28
+ ALLOWANCE_TYPE = "2" # 賣方開立. Amego rejects 1 since 2025-01-01
29
+ # The only rates TaxRate takes (docs, section 4.2).
30
+ TAX_RATES = [0r, Rational(5, 100)].freeze
31
+ MOBILE_MEMBER = /\A09\d{8}\z/
32
+
33
+ MAX_ORDER_ID = 40
34
+ MAX_DESCRIPTION = 256
35
+ MAX_ALLOWANCE_NUMBER = 16
36
+
37
+ # provider_options key => f0401 field, for fields with no unified home.
38
+ ISSUE_OPTIONS = {
39
+ "track_api_code" => "TrackApiCode",
40
+ "brand_name" => "BrandName",
41
+ "detail_amount_round" => "DetailAmountRound",
42
+ "tax_adjustment" => "TaxAdjustment"
43
+ }.freeze
44
+
45
+ module_function
46
+
47
+ # +f0401+ data from a parsed {IssueInvoiceInput}.
48
+ def issue(parsed)
49
+ b2b = parsed.resolved_category == InvoiceCategory::B2B
50
+ exclusive = parsed.price_mode == PriceMode::TAX_EXCLUSIVE
51
+ options = string_keys(parsed.provider_options)
52
+ types = parsed.item_tax_types
53
+ check_issue!(parsed, types, b2b, exclusive)
54
+ breakdown = parsed.tax_breakdown
55
+
56
+ data = {
57
+ "OrderId" => parsed.order_id.to_s,
58
+ "BuyerIdentifier" => b2b ? parsed.buyer.ubn.to_s : CONSUMER_ID,
59
+ "BuyerName" => buyer_name(parsed.buyer, b2b),
60
+ "BuyerAddress" => parsed.buyer&.address.to_s,
61
+ "BuyerTelephoneNumber" => parsed.buyer&.phone.to_s,
62
+ "BuyerEmailAddress" => parsed.buyer&.email.to_s,
63
+ "MainRemark" => parsed.remark.to_s,
64
+ **carrier_fields(parsed.carrier, parsed.buyer),
65
+ "NPOBAN" => parsed.donation&.npoban.to_s,
66
+ "ProductItem" => parsed.items.zip(types).map { |item, type| issue_item(item, type) },
67
+ **issue_totals(breakdown, b2b),
68
+ "TaxType" => types.uniq.size > 1 ? MIXED_TAX_CODE : TAX_TYPE.fetch(types.first),
69
+ "TaxRate" => number(parsed.tax_rate),
70
+ "DetailVat" => exclusive ? "0" : "1"
71
+ }
72
+ if parsed.zero_rated?
73
+ data["CustomsClearanceMark"] = parsed.customs_clearance_mark
74
+ data["ZeroTaxRateReason"] = parsed.zero_tax_rate_reason
75
+ end
76
+ ISSUE_OPTIONS.each { |key, field| data[field] = options[key].to_s if options.key?(key) }
77
+ data
78
+ end
79
+
80
+ # +f0501+ data: one invoice per call. The core checks the reason's length.
81
+ def void(parsed)
82
+ [{ "CancelInvoiceNumber" => parsed.invoice.number.to_s, "CancelReason" => parsed.reason.to_s }]
83
+ end
84
+
85
+ # +g0401+ data. +original+ carries the facts about the original invoice
86
+ # that the reference may not have: +buyer_identifier+, +buyer_name+ and
87
+ # +invoice_datetime+.
88
+ def allowance(parsed, original, allowance_date)
89
+ number = parsed.allowance_id.to_s
90
+ # Amego sends allowance_id as the MIG AllowanceNumber. Other providers
91
+ # number an allowance themselves, so this limit is Amego's.
92
+ max!(number, MAX_ALLOWANCE_NUMBER, "allowance_id")
93
+ breakdown = parsed.tax_breakdown
94
+ refuse_special!(breakdown.lines.map(&:tax_type))
95
+ check_rate!(parsed.tax_rate)
96
+ invoice_date = ymd(original[:invoice_datetime])
97
+
98
+ [{
99
+ "AllowanceNumber" => number,
100
+ "AllowanceDate" => allowance_date.strftime("%Y%m%d"),
101
+ "AllowanceType" => ALLOWANCE_TYPE,
102
+ "BuyerIdentifier" => original[:buyer_identifier].to_s,
103
+ "BuyerName" => original[:buyer_name].to_s,
104
+ "ProductItem" => parsed.items.zip(breakdown.lines).map do |item, line|
105
+ allowance_item(item, line).merge("OriginalInvoiceNumber" => parsed.invoice.number.to_s,
106
+ "OriginalInvoiceDate" => invoice_date)
107
+ end,
108
+ "TaxAmount" => breakdown.tax_amount,
109
+ "TotalAmount" => breakdown.sales_amount
110
+ }]
111
+ end
112
+
113
+ # +g0501+ data.
114
+ def void_allowance(parsed)
115
+ [{ "CancelAllowanceNumber" => parsed.allowance.allowance_number.to_s }]
116
+ end
117
+
118
+ # +invoice_query+ data. The order id wins when the reference has both.
119
+ def query(reference)
120
+ if reference.order_id.nil?
121
+ { "type" => "invoice", "invoice_number" => reference.number.to_s }
122
+ else
123
+ { "type" => "order", "order_id" => reference.order_id.to_s }
124
+ end
125
+ end
126
+
127
+ # --- issue -------------------------------------------------------------
128
+
129
+ def check_issue!(parsed, types, b2b, exclusive)
130
+ max!(parsed.order_id.to_s, MAX_ORDER_ID, "order_id")
131
+ unsupported!("Amego takes tax-exclusive prices only for a B2B invoice") if exclusive && !b2b
132
+ refuse_special!(types)
133
+ check_rate!(parsed.tax_rate)
134
+ end
135
+
136
+ def refuse_special!(types)
137
+ return unless types.include?(TaxType::SPECIAL)
138
+
139
+ raise UnsupportedError.new("Amego adapter does not support special tax (特種稅額)",
140
+ provider: Client::PROVIDER)
141
+ end
142
+
143
+ # The core has checked that +rate+ is a MIG rate. Amego takes two of them.
144
+ def check_rate!(rate)
145
+ return if TAX_RATES.include?(rate)
146
+
147
+ raise UnsupportedError.new("Amego takes a tax rate of 0 or 0.05 only, got #{number(rate)}",
148
+ provider: Client::PROVIDER)
149
+ end
150
+
151
+ # The MIG totals from the core's breakdown (docs, section 4.3). A B2C
152
+ # invoice keeps the tax inside SalesAmount, as F0401 does.
153
+ def issue_totals(breakdown, b2b)
154
+ sales = breakdown.taxable_amount
155
+ tax = breakdown.tax_amount
156
+ sales, tax = sales + tax, 0 unless b2b
157
+ { "SalesAmount" => sales, "FreeTaxSalesAmount" => breakdown.tax_free_amount,
158
+ "ZeroTaxSalesAmount" => breakdown.zero_rated_amount, "TaxAmount" => tax,
159
+ "TotalAmount" => breakdown.total_amount }
160
+ end
161
+
162
+ def buyer_name(buyer, b2b)
163
+ name = buyer&.name.to_s
164
+ return name unless name.empty?
165
+
166
+ b2b ? buyer.ubn.to_s : CONSUMER_NAME
167
+ end
168
+
169
+ # Visible and hidden codes are the same. A member carrier without a code
170
+ # uses the buyer's email, else +a+ and the buyer's mobile number.
171
+ def carrier_fields(carrier, buyer)
172
+ return { "CarrierType" => "", "CarrierId1" => "", "CarrierId2" => "" } unless carrier
173
+
174
+ code = carrier.code.to_s
175
+ code = member_code(buyer) if code.empty? && carrier.type == CarrierType::MEMBER
176
+ invalid!("a #{carrier.type} carrier needs a code") if code.empty?
177
+
178
+ { "CarrierType" => CARRIER_TYPE.fetch(carrier.type), "CarrierId1" => code, "CarrierId2" => code }
179
+ end
180
+
181
+ def member_code(buyer)
182
+ email = buyer&.email.to_s
183
+ return email unless email.empty?
184
+
185
+ phone = buyer&.phone.to_s.delete("- ")
186
+ phone.match?(MOBILE_MEMBER) ? "a#{phone}" : ""
187
+ end
188
+
189
+ def issue_item(item, type)
190
+ description = item.description.to_s
191
+ max!(description, MAX_DESCRIPTION, "item description")
192
+ {
193
+ "Description" => description,
194
+ "Quantity" => number(item.quantity),
195
+ "Unit" => item.unit.to_s,
196
+ "UnitPrice" => number(item.unit_price),
197
+ "Amount" => number(item.amount),
198
+ "Remark" => item.remark.to_s,
199
+ "TaxType" => TAX_TYPE.fetch(type)
200
+ }
201
+ end
202
+
203
+ # --- allowance ---------------------------------------------------------
204
+
205
+ # Amego wants allowance amounts without tax, and an integer +Tax+ on each
206
+ # item (docs, section 4.3). Both come from the core's line. The unit price
207
+ # is the amount over the quantity, rounded to 7 decimal places, so
208
+ # +UnitPrice × Quantity+ can miss +Amount+ by that rounding: 94 over 3 is
209
+ # 31.3333333.
210
+ def allowance_item(item, line)
211
+ description = item.description.to_s
212
+ max!(description, MAX_DESCRIPTION, "item description")
213
+ {
214
+ "OriginalDescription" => description,
215
+ "Quantity" => number(item.quantity),
216
+ "UnitPrice" => number(unit_price(line.net_amount, item.quantity)),
217
+ "Amount" => number(line.net_amount),
218
+ "Tax" => line.tax,
219
+ "TaxType" => TAX_TYPE.fetch(line.tax_type)
220
+ }
221
+ end
222
+
223
+ def unit_price(amount, quantity)
224
+ quantity = quantity.to_r
225
+ quantity.zero? ? amount.to_r : amount.to_r / quantity
226
+ end
227
+
228
+ # --- helpers -----------------------------------------------------------
229
+
230
+ # Amego takes up to 7 decimals. Whole numbers go out without a point. The
231
+ # core has already read every number as exact.
232
+ # Rounds to 7 decimal places first, so a value that rounds to a whole
233
+ # number is written without a point: "100", not "100.".
234
+ def number(value)
235
+ rational = value.to_r.round(7)
236
+ return rational.to_i.to_s if rational.denominator == 1
237
+
238
+ format("%.7f", rational).sub(/0+\z/, "")
239
+ end
240
+
241
+ # A Time → "Ymd" in Taipei time.
242
+ def ymd(time)
243
+ Taipei.date(time, provider: Client::PROVIDER).strftime("%Y%m%d")
244
+ end
245
+
246
+ # The core checks the MIG lengths. A shorter limit of Amego's own is
247
+ # UnsupportedError: another provider may take the value
248
+ # (docs/providers/README.md, "The unified model").
249
+ def max!(value, limit, field)
250
+ return if value.length <= limit
251
+
252
+ unsupported!("Amego takes a #{field} of at most #{limit} characters")
253
+ end
254
+
255
+ # The input breaks a MIG rule, or lacks what the call needs.
256
+ def invalid!(message)
257
+ raise ValidationError.new(message, provider: Client::PROVIDER)
258
+ end
259
+
260
+ # The MIG allows the input, but Amego does not take it.
261
+ def unsupported!(message)
262
+ raise UnsupportedError.new(message, provider: Client::PROVIDER)
263
+ end
264
+
265
+ def string_keys(hash)
266
+ (hash || {}).to_h.transform_keys(&:to_s)
267
+ end
268
+ end
269
+ end
270
+ end
@@ -0,0 +1,272 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "set"
4
+
5
+ module Einvoice
6
+ module Amego
7
+ # {Einvoice::Provider} over Amego 光貿's JSON API, with 自動配號: Amego picks
8
+ # the invoice number.
9
+ #
10
+ # docs/providers/amego/api.md describes the API and the choices below.
11
+ #
12
+ # Two behaviours to know:
13
+ #
14
+ # - A void is queued. Amego accepts it at once, but a query right after it
15
+ # can still report the invoice as issued.
16
+ # - An allowance needs the original invoice's buyer and date. The reference
17
+ # has the date and the 統一編號, but not the buyer's name, so the adapter
18
+ # queries the invoice for it, unless +provider_options+ gives +buyer_name+
19
+ # and the reference has +invoice_datetime+. The query only works within
20
+ # 180 days.
21
+ class Provider < ::Einvoice::Provider
22
+ CAPABILITIES = Set[
23
+ Capability::ISSUE,
24
+ Capability::VOID,
25
+ Capability::ALLOWANCE,
26
+ Capability::VOID_ALLOWANCE,
27
+ Capability::QUERY,
28
+ Capability::QUERY_BY_ORDER_ID,
29
+ Capability::B2B,
30
+ Capability::MIXED_TAX,
31
+ Capability::CARRIER_VALIDATION
32
+ ].freeze
33
+
34
+ # The barcode code for a mobile barcode that is not registered.
35
+ UNREGISTERED_BARCODE = "9000113"
36
+
37
+ VOID_TYPES = %w[C0501 A0501 A0201 A0202].freeze
38
+ ISSUE_TYPES = %w[C0401 A0401 A0101 A0102].freeze
39
+ LIVE_ALLOWANCE_TYPES = %w[D0401 G0401 B0401 B0101 B0102].freeze
40
+
41
+ attr_reader :capabilities, :client
42
+
43
+ def initialize(ban:, app_key:, base_url: Client::BASE_URL, timeout: 30, clock: -> { Time.now })
44
+ super()
45
+ @client = Client.new(ban: ban, app_key: app_key, base_url: base_url, timeout: timeout, clock: clock)
46
+ @clock = clock
47
+ @capabilities = CAPABILITIES
48
+ end
49
+
50
+ def name
51
+ Client::PROVIDER
52
+ end
53
+
54
+ # Call any Amego path with a raw payload, for example
55
+ #
56
+ # provider.raw("/json/barcode", { barCode: "/ABC1234" })
57
+ #
58
+ # The signing and the error mapping are applied as usual. Brace the Hash:
59
+ # an unbraced one is read as keyword arguments.
60
+ def raw(path, payload)
61
+ @client.request(path, payload)
62
+ end
63
+
64
+ # 開立發票 (+f0401+).
65
+ def issue(input)
66
+ parsed = Input.issue(input, provider: name)
67
+ assert_currency_supported!(parsed.currency)
68
+ result = @client.request("/json/f0401", Payload.issue(parsed))
69
+
70
+ IssueInvoiceResult.new(
71
+ invoice_number: result["invoice_number"].to_s,
72
+ invoice_datetime: unix_time(result["invoice_time"]),
73
+ random_code: result["random_number"].to_s,
74
+ order_id: parsed.order_id,
75
+ total_amount: parsed.amount.total_amount,
76
+ buyer_ubn: parsed.buyer&.ubn,
77
+ tax_type: parsed.resolved_tax_type,
78
+ tax_rate: parsed.tax_rate,
79
+ status: InvoiceStatus::ISSUED,
80
+ raw: result
81
+ )
82
+ end
83
+
84
+ # 作廢發票 (+f0501+). The void is queued: see the class comment.
85
+ def void(input)
86
+ parsed = Input.void(input, provider: name)
87
+ result = @client.request("/json/f0501", Payload.void(parsed))
88
+ VoidInvoiceResult.new(invoice_number: parsed.invoice.number, status: InvoiceStatus::VOIDED, raw: result)
89
+ end
90
+
91
+ # 開立折讓 (+g0401+). The seller assigns the allowance number, so the
92
+ # result's +allowance_number+ is the input's +allowance_id+. The allowance
93
+ # date is today in Taipei.
94
+ def allowance(input)
95
+ parsed = Input.allowance(input, provider: name)
96
+ allowance_date = Taipei.date(@clock.call)
97
+ data = Payload.allowance(parsed, original_invoice(parsed), allowance_date)
98
+ result = @client.request("/json/g0401", data)
99
+
100
+ AllowanceResult.new(
101
+ allowance_number: parsed.allowance_id.to_s,
102
+ invoice_number: parsed.invoice.number,
103
+ allowance_date: allowance_date,
104
+ total_amount: parsed.amount.total_amount,
105
+ raw: result
106
+ )
107
+ end
108
+
109
+ # 作廢折讓 (+g0501+). Amego takes no reason here.
110
+ def void_allowance(input)
111
+ parsed = Input.void_allowance(input, provider: name)
112
+ result = @client.request("/json/g0501", Payload.void_allowance(parsed))
113
+ VoidAllowanceResult.new(allowance_number: parsed.allowance.allowance_number, raw: result)
114
+ end
115
+
116
+ # 查詢發票 (+invoice_query+), by order id when the reference has one, else
117
+ # by invoice number. Within 180 days of the invoice.
118
+ def query(input)
119
+ reference = Input.query(input, provider: name).invoice
120
+ assert_supports!(Capability::QUERY_BY_ORDER_ID) if reference.order_id
121
+ build_query_result(fetch_invoice(Payload.query(reference)))
122
+ end
123
+
124
+ # Whether a carrier is registered (+barcode+). Amego can check a 手機條碼
125
+ # only. For a donation code, use {Einvoice::MOF::DonationCodes}.
126
+ def validate_carrier(carrier)
127
+ parsed = Input.carrier(carrier, provider: name)
128
+ unless parsed.type == CarrierType::MOBILE_BARCODE
129
+ raise UnsupportedError.new("Amego can check a mobile barcode only, not #{parsed.type}", provider: name)
130
+ end
131
+
132
+ begin
133
+ @client.request("/json/barcode", { "barCode" => parsed.code })
134
+ rescue Error => e
135
+ return false if e.raw_code == UNREGISTERED_BARCODE
136
+
137
+ raise
138
+ end
139
+ true
140
+ end
141
+
142
+ private
143
+
144
+ def fetch_invoice(payload)
145
+ data = @client.request("/json/invoice_query", payload)["data"]
146
+ return data if data.is_a?(Hash)
147
+
148
+ raise ProviderError.new("Amego returned no invoice data", provider: name, raw: data)
149
+ end
150
+
151
+ # The original invoice's buyer and date (docs, section 4.1). The reference
152
+ # has the date and the 統一編號. The buyer's name comes from
153
+ # +provider_options+, else from a query. A failed query is the provider's
154
+ # error, not the invoice's: a NotFoundError would read as "the invoice of
155
+ # this call does not exist".
156
+ def original_invoice(parsed)
157
+ reference = parsed.invoice
158
+ buyer_name = Payload.string_keys(parsed.provider_options)["buyer_name"]
159
+ if buyer_name && reference.invoice_datetime
160
+ return { buyer_identifier: reference.buyer_ubn || Payload::CONSUMER_ID, buyer_name: buyer_name,
161
+ invoice_datetime: reference.invoice_datetime }
162
+ end
163
+
164
+ found = lookup(reference.number)
165
+ if found.invoice_datetime.nil?
166
+ raise ProviderError.new("allowance needs the invoice date; the invoice found by number has none",
167
+ provider: name, reason: Reason::LOOKUP_FAILED)
168
+ end
169
+ { buyer_identifier: reference.buyer_ubn || found.buyer.ubn || Payload::CONSUMER_ID,
170
+ buyer_name: buyer_name || found.buyer.name.to_s,
171
+ invoice_datetime: reference.invoice_datetime || found.invoice_datetime }
172
+ end
173
+
174
+ def lookup(number)
175
+ build_query_result(fetch_invoice(Payload.query(InvoiceReference.new(number: number))))
176
+ rescue Error => e
177
+ raise ProviderError.new("allowance needs the invoice's buyer and date; looking them up failed: #{e.message}",
178
+ provider: name, reason: Reason::LOOKUP_FAILED, cause: e)
179
+ end
180
+
181
+ # invoice_query sends both totals for B2C and B2B [live], so a missing one
182
+ # is an error. So is a value that is not a whole number.
183
+ def build_query_result(data)
184
+ tax = Number.response_integer!(data["tax_amount"], field: "tax_amount", provider: name, raw: data)
185
+ total = Number.response_integer!(data["total_amount"], field: "total_amount", provider: name, raw: data)
186
+ tax_type = INVOICE_TAX_TYPE[data["tax_type"].to_s]
187
+ items = TaxType.fill_items(Array(data["product_item"]).map { |row| build_item(row) }, tax_type)
188
+ QueryInvoiceResult.new(
189
+ invoice_number: data["invoice_number"].to_s,
190
+ invoice_datetime: taipei_time(data["invoice_date"], data["invoice_time"]),
191
+ random_code: data["random_number"].to_s,
192
+ order_id: presence(data["order_id"]),
193
+ status: status_of(data),
194
+ amount: AmountSummary.new(sales_amount: total - tax, tax_amount: tax, total_amount: total),
195
+ buyer: build_buyer(data),
196
+ items: items,
197
+ tax_type: tax_type,
198
+ tax_rate: query_rate(data["tax_rate"]),
199
+ raw: data
200
+ )
201
+ end
202
+
203
+ # invoice_query +tax_type+ → unified 課稅別. 9 is mixed.
204
+ INVOICE_TAX_TYPE = Payload::TAX_TYPE.invert.merge(Payload::MIXED_TAX_CODE => TaxType::MIXED).freeze
205
+
206
+ # A rate that is not a MIG rate reads as nil, so an allowance has to give
207
+ # one.
208
+ def query_rate(reported)
209
+ Input.mig_rate!(reported, "tax_rate", name)
210
+ rescue ValidationError
211
+ nil
212
+ end
213
+
214
+ # docs, section 4.4. A cancelled (+C0701+) or rejected (+A0301+, +A0302+)
215
+ # invoice has no unified status, so it is nil. The raw type stays in
216
+ # +raw["invoice_type"]+.
217
+ def status_of(data)
218
+ type = data["invoice_type"].to_s
219
+ return InvoiceStatus::VOIDED if VOID_TYPES.include?(type)
220
+ return nil unless ISSUE_TYPES.include?(type)
221
+
222
+ live = Array(data["allowance"]).any? { |row| LIVE_ALLOWANCE_TYPES.include?(row["invoice_type"].to_s) }
223
+ live ? InvoiceStatus::ALLOWANCE : InvoiceStatus::ISSUED
224
+ end
225
+
226
+ def build_buyer(data)
227
+ id = data["buyer_identifier"].to_s
228
+ Buyer.new(name: presence(data["buyer_name"]),
229
+ ubn: id.empty? || id == Payload::CONSUMER_ID ? nil : id,
230
+ email: presence(data["buyer_email_address"]),
231
+ address: presence(data["buyer_address"]),
232
+ phone: presence(data["buyer_telephone_number"]))
233
+ end
234
+
235
+ def build_item(row)
236
+ InvoiceItem.new(
237
+ description: row["description"].to_s,
238
+ quantity: item_number(row, "quantity"),
239
+ unit_price: item_number(row, "unit_price"),
240
+ amount: item_number(row, "amount"),
241
+ unit: presence(row["unit"]),
242
+ tax_type: Payload::TAX_TYPE.invert[row["tax_type"].to_s],
243
+ remark: presence(row["remark"])
244
+ )
245
+ end
246
+
247
+ # A missing item number is nil, not 0.
248
+ def item_number(row, field)
249
+ Number.response_plain(row[field], field: "product_item #{field}", provider: name, raw: row)
250
+ end
251
+
252
+ def presence(value)
253
+ string = value.to_s
254
+ string.empty? ? nil : string
255
+ end
256
+
257
+ def unix_time(value)
258
+ seconds = Integer(value.to_s, exception: false)
259
+ seconds && Time.at(seconds).getlocal("+08:00")
260
+ end
261
+
262
+ # "20221201" and "09:56:38" (UTC+8) → Time, or nil without a date.
263
+ def taipei_time(date, time)
264
+ match = /\A(\d{4})(\d{2})(\d{2})\z/.match(date.to_s)
265
+ return nil unless match
266
+
267
+ hour, minute, second = time.to_s.split(":").map(&:to_i)
268
+ Time.new(*match.captures.map(&:to_i), hour.to_i, minute.to_i, second.to_i, "+08:00")
269
+ end
270
+ end
271
+ end
272
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "einvoice"
4
+ require "einvoice/amego/errors"
5
+ require "einvoice/amego/client"
6
+ require "einvoice/amego/payload"
7
+ require "einvoice/amego/provider"
8
+
9
+ module Einvoice
10
+ # Adapter for Amego 光貿科技's JSON e-invoice API.
11
+ #
12
+ # The wire format is a form POST with a JSON +data+ field and an MD5 +sign+.
13
+ # There is no encryption. None of that reaches application code: {Provider}
14
+ # exposes only the unified model.
15
+ #
16
+ # provider = Einvoice::Amego::Provider.new(**Einvoice::Amego::SANDBOX)
17
+ # provider.issue(order_id: "ORDER_1", ...) # => Einvoice::IssueInvoiceResult
18
+ module Amego
19
+ # Amego's published shared **test** account. Every developer uses it, so
20
+ # never use it for anything real. Amego has one host for test and
21
+ # production: these credentials are what make a call a test.
22
+ SANDBOX = {
23
+ ban: "12345678",
24
+ app_key: "sHeq7t8G1wiQvhAuIM27"
25
+ }.freeze
26
+ end
27
+ end