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
data/README.md CHANGED
@@ -1,419 +1,378 @@
1
1
  # Einvoice
2
- [![Build Status](https://github.com/abookyun/einvoice/actions/workflows/build.yml/badge.svg)](https://github.com/abookyun/einvoice/actions/workflows/build.yml)
3
- [![codecov](https://codecov.io/github/abookyun/einvoice/graph/badge.svg?token=yxJNmXiUyp)](https://codecov.io/github/abookyun/einvoice)
4
2
 
5
- > **The 1.x line is moving to maintenance mode.** A provider-agnostic 2.0
6
- > rewrite is in progress on `main`; once it lands, 1.x continues on the
7
- > [`1-x-stable`](https://github.com/abookyun/einvoice/tree/1-x-stable) branch.
8
- > If you depend on the current Tradevan client, pin `~> 1.4`.
3
+ English | [繁體中文](README.zh-TW.md)
9
4
 
10
- ## What's E-Invoice
5
+ [![Build Status](https://github.com/abookyun/einvoice/actions/workflows/build.yml/badge.svg)](https://github.com/abookyun/einvoice/actions/workflows/build.yml) [![codecov](https://codecov.io/github/abookyun/einvoice/graph/badge.svg?token=yxJNmXiUyp)](https://codecov.io/github/abookyun/einvoice)
11
6
 
12
- To support the thriving e-commerce industry and lower the business costs and barriers associated with printing paper receipts, the Taiwan Executive Yuan announced plans in August 2000 to implement electronic receipts in Taiwan and launched a comprehensive project in May 2010 to promote e-invoice applications. This initiative employs innovative approaches such as allowing consumers to claim virtual receipts via multiple devices, offering automatic checking of receipt lottery numbers, and providing a variety of channels for retailers to issue receipts.
7
+ A **Taiwan e-invoice SDK** that works with several providers (加值中心). Every provider follows the same 財政部 standard, MIG 4.1. Only the wire format differs: field names, signing and the envelope. So this gem defines the five operations once: issue (開立), void (作廢), allowance (折讓), void allowance (折讓作廢) and query (查詢). Your code calls `Einvoice::Provider` with the unified types, and each provider is an adapter behind it. To move to another provider, you start with a new constructor, not new business code.
13
8
 
14
- Hence, there are several e-invoice services for B2B, B2C in Taiwan as the intermediate and value-adding platform like [CHT](https://invoice.cht.com.tw/invoice/login.jsp), [allPay](https://www.allpay.com.tw/Business/invoice), [Tradevan](http://www.tradevan.com.tw/services/index.do?act=services_info&type=16), Neweb, ..[etc](https://www.einvoice.nat.gov.tw/index!showAddCenter?linkIsNew=Y&CSRT=3716270004994188830).
9
+ The providers still differ in what they can do. Each adapter says so through its capabilities, `query_statuses` and `UnsupportedError`, so you can check a provider before you switch to it.
15
10
 
16
- ## Supported E-Invoice Providers
11
+ > **2.0 is a rewrite, and 1.x is in maintenance mode.** 1.x was a client for one provider, Tradevan, with a different API. If you depend on it, pin `~> 1.4`. It continues on the [`1-x-stable`](https://github.com/abookyun/einvoice/tree/1-x-stable) branch. 2.0 is not backward compatible. To move to 2.0, read [Upgrading from 1.x to 2.0](docs/upgrading-to-2.0.md). The [changelog](CHANGELOG.md) lists every change.
17
12
 
18
- * Tradevan
13
+ ## Providers at a glance
14
+
15
+ | | ECPay 綠界 | Amego 光貿 | ezPay 簡單行動支付 | Tradevan 關貿 DEFAULTAPI |
16
+ | --- | --- | --- | --- | --- |
17
+ | Status | Checked against ECPay's public stage | Checked against Amego's public test account | Experimental: built from ezPay's manuals, not run against ezPay | Experimental: ported from the 1.x client, not run against the live API |
18
+ | B2B (`B2B`) | Yes | Yes | Yes | Yes |
19
+ | Mixed tax (`MIXED_TAX`) | Yes | Yes | B2C only | No |
20
+ | Special tax (特種稅額) | Yes | No | No | No |
21
+ | Query by order id (`QUERY_BY_ORDER_ID`) | Yes | Yes | No | No |
22
+ | Carrier validation (`CARRIER_VALIDATION`) | Mobile barcode only | Mobile barcode only | No | No |
23
+ | Foreign currency (`FOREIGN_CURRENCY`) | No | No | No | No |
24
+ | `query_statuses` | All | All | `:voided` | `:allowance` |
25
+
26
+ All four have the five operations. A "No" raises `UnsupportedError`. The [provider notes](docs/providers/README.md) compare the wire formats and the test accounts.
27
+
28
+ Other providers may follow. Most have less complete docs and no public test account, so an adapter built from docs alone stays uncertain until it runs in production.
19
29
 
20
30
  ## Installation
21
31
 
22
- Add this line to your application's Gemfile:
32
+ 2.0 is in beta, and its API may still change before 2.0.0. It needs Ruby 3.3 or newer. Pin the exact version:
23
33
 
24
34
  ```ruby
25
- gem 'einvoice'
35
+ gem "einvoice", "2.0.0.beta1"
26
36
  ```
27
37
 
28
- And then execute:
29
-
30
- $ bundle
38
+ To follow the latest work, install from `main` instead:
31
39
 
32
- Or install it yourself as:
40
+ ```ruby
41
+ gem "einvoice", git: "https://github.com/abookyun/einvoice", branch: "main"
42
+ ```
33
43
 
34
- $ gem install einvoice
44
+ From 2.0.0 on, the gem follows [Semantic Versioning](https://semver.org/), with three limits:
35
45
 
36
- ## Usage
46
+ - The experimental adapters, ezPay and Tradevan, may change in a minor release. Nobody has run them against the provider yet, so the first real run may need a change.
47
+ - `tax_breakdown` may get new fields, or change one, in a minor release. The adapters read it, and a new provider may need more from it.
48
+ - A new check that makes the input follow the MIG is a fix, not a breaking change. An input that breaks the MIG is a wrong filing, even when a provider takes it.
37
49
 
38
- ### Configure
50
+ `require "einvoice"` loads the core and `MockProvider` only. Require the provider you use, and only that one is loaded:
39
51
 
40
52
  ```ruby
41
- Einvoice.configure do |config|
42
- config.endpoint = ENV['EINVOICE_ENDPOINT']
43
- # endpoint_url will override endpoint for testing purpose
44
- # config.endpoint_url = ENV['EINVOICE_ENDPOINT_URL']
45
- config.client_id = ENV['EINVOICE_CLIENT_ID']
46
- config.client_secret = ENV['EINVOICE_CLIENT_SECRET']
47
- config.encryption_keys = ENV['ENCRYPTION_KEYS']
48
- config.format = "json"
49
- # config.ssl_verify = false # disable TLS certificate verification (default: true)
50
- end
53
+ require "einvoice/ecpay" # or einvoice/amego, einvoice/ezpay, einvoice/tradevan
54
+ require "einvoice/mof" # the 財政部 lookups, if you use them
51
55
  ```
52
- ### SSL certificate verification
53
56
 
54
- By default, `einvoice` verifies the TLS certificate of the configured
55
- endpoint (`config.ssl_verify` defaults to `true`). If you need to disable
56
- this — for example when testing against an endpoint with an incomplete
57
- certificate chain — you can opt out:
57
+ ## Usage
58
58
 
59
- ```ruby
60
- config.ssl_verify = false
61
- ```
59
+ ### Issue, query and void
62
60
 
63
- Or per-provider:
61
+ Depend on the `Einvoice::Provider` contract, not on one adapter. You build each provider as an instance, and there is no global configuration. So an app with many merchants holds one provider for each set of credentials.
64
62
 
65
63
  ```ruby
66
- Einvoice::Tradevan::Provider.new(ssl_verify: false)
64
+ # Every adapter is an Einvoice::Provider. MockProvider runs in memory.
65
+ provider = Einvoice::MockProvider.new
66
+
67
+ issued = provider.issue(
68
+ order_id: "ORDER_1",
69
+ buyer: { email: "buyer@example.com" }, # no ubn, so B2C (二聯式)
70
+ items: [
71
+ { description: "咖啡拿鐵", quantity: 1, unit_price: 100, amount: 100 }
72
+ ],
73
+ tax_type: "TAXABLE",
74
+ price_mode: "TAX_INCLUSIVE",
75
+ carrier: { type: "MEMBER" }
76
+ )
77
+
78
+ issued.invoice_number # => "MK10000000"
79
+ issued.status # => :issued
80
+
81
+ found = provider.query(invoice: issued.reference)
82
+ found.status # => :issued, or nil when the provider cannot tell
83
+ provider.query_statuses # => [:issued, :voided, :allowance]
84
+
85
+ provider.void(invoice: issued.reference, reason: "客戶取消")
67
86
  ```
68
87
 
69
- ### Initialize
88
+ Inputs take plain hashes, with string or symbol keys. An enum field takes the symbol (`:taxable`) or a wire-style string (`"TAXABLE"`). Before anything goes over the network, the core checks the input against the MIG and turns it into immutable value objects. A bad input raises `Einvoice::ValidationError`. A value object that you build with `.new` gets the same checks. [Input rules](#input-rules) lists them.
70
89
 
71
- ```ruby
72
- client = Einvoice::Client.new(Einvoice::Tradevan::Provider.new)
73
- ```
90
+ ### References
74
91
 
75
- ### Issue an invoice (開立電子發票)
92
+ `issued.reference` is an `InvoiceReference`. It holds what a provider asks for when you later void the invoice, make an allowance on it, or query it:
76
93
 
77
- ```ruby
78
- payload = {
79
- companyUn: "12345678",
80
- orgId: "ABCDE",
81
- type: "I",
82
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
83
- transactionNumber: "53b2a44e4b3c",
84
- transactionDate: "20160425",
85
- transactionTime: "12:34:56",
86
- total: "20000",
87
- paperPrintMode: "0",
88
- invoiceAlarmMode: "4",
89
- donate: "N",
90
- donationUnit: nil,
91
- carrierType: "3J0002",
92
- carrierId: "TP03000001234567",
93
- carrierIdHidden: "TP03000001234567",
94
- receiverName: "John Appleseed",
95
- receiverAddrZip: "95014",
96
- receiverAddrRoad: "1 Infinite Loop - Cupertino CA",
97
- receiverEmail: "john@gmail.com",
98
- receiverMobile: "415-284-0579",
99
- memberId: nil,
100
- itemList: [
101
- {
102
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
103
- serialNumber: "0001",
104
- productName: "Coffee Latte",
105
- qty: "4000",
106
- price: "5",
107
- itemTotal: "20000",
108
- taxType: "T",
109
- tax: "952"
110
- }
111
- ]
112
- }
113
- ```
94
+ - the number, `invoice_datetime`, `random_code`, `order_id`, `total_amount` and `buyer_ubn`
95
+ - `tax_type` and `tax_rate`, which an allowance takes
96
+
97
+ Store it with your order, and pass it back later:
114
98
 
115
99
  ```ruby
116
- result = client.issue(payload)
117
- result.successful?
118
- #=> true
119
- result.data
120
- #=>
121
- # {
122
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
123
- # "issueStatus"=>"Y",
124
- # "failReason"=>"",
125
- # "invoiceNumber"=>"GX38551078",
126
- # "checkNumber"=>"4229",
127
- # "invoiceDate"=>"20160425",
128
- # "invoiceTime"=>"12:34:58",
129
- # "texclusiveAmount"=>"19048",
130
- # "oexclusiveAmount"=>"0",
131
- # "zexclusiveAmount"=>"0",
132
- # "tax"=>"952",
133
- # "inclusiveAmount"=>"20000",
134
- # "mainRemark"=>"",
135
- # "invoiceType"=>"",
136
- # "invoiceStatus"=>"V",
137
- # "allowanceNumber"=>"",
138
- # "allowanceDate"=>"",
139
- # "allowanceExclusiveAmount"=>"",
140
- # "allowanceTax"=>"",
141
- # "allowanceTotalAmount"=>"0",
142
- # "allowanceStatus"=>""
143
- # }
100
+ stored = issued.reference.to_h # save this with your order
101
+ provider.void(invoice: stored, reason: "客戶取消")
144
102
  ```
145
103
 
146
- ### Cancel an invoice (作廢電子發票)
104
+ - `to_h` holds JSON-safe values only, so it fits a JSON column. `invoice_datetime` is an ISO 8601 string in UTC+8.
105
+ - A stored time has to carry its offset. `"2026-08-01 10:00"` is refused, so that it is not read in the wrong zone. A date alone, such as `"2026-08-01"`, is that day in Taipei.
106
+ - You can also pass the `InvoiceReference` itself.
107
+ - A plain invoice number works too. A provider that needs more raises `ValidationError` and names the field.
108
+ - To find an invoice without its number, query `invoice: { order_id: "ORDER_1" }`. The provider has to declare `QUERY_BY_ORDER_ID`.
109
+ - `void_allowance` takes `allowance:`. Pass the `AllowanceReference` from `AllowanceResult#reference`.
147
110
 
148
- ```ruby
149
- payload = {
150
- type: "I",
151
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
152
- invoiceNumber: "GX38551078",
153
- invoicePaperReturned: "Y",
154
- }
155
- ```
111
+ ### Amounts and tax
156
112
 
157
- ```ruby
158
- result = client.cancel(payload)
159
- result.successful?
160
- #=> true
161
- result.data
162
- #=>
163
- # {
164
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
165
- # "voidStatus"=>"Y",
166
- # "failReason"=>"",
167
- # "type"=>"I",
168
- # "invoiceNumber"=>"GX38551078",
169
- # "allowanceNumber"=>""
170
- # }
171
- ```
113
+ The core computes the tax from the items:
172
114
 
173
- ### Issue an allowance (開立折讓單)
115
+ - `price_mode` says if the item amounts include tax.
116
+ - `tax_type` is the tax type of the whole invoice. An item can have its own.
117
+ - `tax_rate` is the rate.
174
118
 
175
- An allowance against a previously issued invoice is sent through `issue` with `type: "A"`. Each item must reference the original invoice (`invoiceNumber` / `invoiceDate`) and carry its tax-exclusive amount (`itemExclude`).
119
+ The result is `input.tax_breakdown`: the amount without tax, the tax and the amount with tax of each line, and the MIG totals. Adapters read it, and do not compute tax themselves. The core never changes your items.
120
+
121
+ Items with different tax types make a mixed-tax invoice (混合稅率). You do not ask for it. A provider without `MIXED_TAX` raises `UnsupportedError`.
122
+
123
+ `amount` is optional. Leave it out, and the core fills it in from the breakdown. Give it, and the core checks it against the breakdown, so your totals cannot drift from the items. An invoice follows F0401. For a consumer, the tax stays inside `sales_amount`. For a business buyer, `tax_amount` is `round(taxable sales × tax_rate)`:
176
124
 
177
125
  ```ruby
178
- payload = {
179
- companyUn: "12345678",
180
- orgId: "ABCDE",
181
- type: "A",
182
- allowanceIdentifier: "12345678_ABCDE_53b2a44e4b3d",
183
- transactionNumber: "53b2a44e4b3d",
184
- transactionDate: "20160426",
185
- paperPrintMode: "0",
186
- invoiceAlarmMode: "4",
187
- allowanceExclusiveAmount: "95",
188
- allowanceTax: "5",
189
- allowanceInclusiveAmount: "100",
190
- allowancePaperReturned: "N",
191
- invoicePaperReturned: "N",
192
- receiverName: "John Appleseed",
193
- receiverEmail: "john@gmail.com",
194
- itemList: [
195
- {
196
- saleIdentifier: "12345678_ABCDE_53b2a44e4b3c",
197
- serialNumber: "0001",
198
- invoiceNumber: "GX38551078",
199
- invoiceDate: "20160425",
200
- productName: "Coffee Latte",
201
- qty: "1000",
202
- price: "100",
203
- itemExclude: "95",
204
- tax: "5",
205
- itemTotal: "100",
206
- taxType: "T"
207
- }
208
- ]
209
- }
126
+ amount: { sales_amount: 100, tax_amount: 0, total_amount: 100 } # 100 with tax, to a consumer (B2C)
127
+ amount: { sales_amount: 95, tax_amount: 5, total_amount: 100 } # 100 with tax, to a business (B2B)
210
128
  ```
211
129
 
130
+ An allowance follows G0401: `sales_amount` excludes tax, for a consumer too. It takes `tax_type` and `tax_rate` from the invoice reference, so pass `issued.reference`, or give them yourself. There is no default, so a zero-rated invoice is never credited with 5% tax. When the invoice has mixed tax, give every item its `tax_type`.
131
+
212
132
  ```ruby
213
- result = client.issue(payload)
214
- result.successful?
215
- #=> true
133
+ provider.allowance(
134
+ invoice: issued.reference, allowance_id: "AL_1", price_mode: "TAX_INCLUSIVE",
135
+ items: [{ description: "退貨", quantity: 1, unit_price: 100, amount: 100 }],
136
+ amount: { sales_amount: 95, tax_amount: 5, total_amount: 100 }
137
+ )
216
138
  ```
217
139
 
218
- Notes:
140
+ ### Errors
219
141
 
220
- * `allowanceIdentifier` must be prefixed with `"#{companyUn}_#{orgId}_"`, like `saleIdentifier` on invoices.
221
- * `allowanceExclusiveAmount` + `allowanceTax` = `allowanceInclusiveAmount`.
142
+ Every failure is a subclass of `Einvoice::Error`. It carries:
222
143
 
223
- ### Void an allowance (作廢折讓單)
144
+ - a stable `#code`
145
+ - the provider's own `#raw_code` and `#raw_message`
146
+ - an optional `#reason`, which says what to do next
147
+ - `#group`, which says which side failed: `:invoice` (the request breaks a 財政部 rule, or the invoice is not in the state it needs) or `:provider` (the account, the connection, or the provider's own service)
224
148
 
225
- ```ruby
226
- payload = {
227
- type: "A",
228
- companyUn: "12345678",
229
- allowanceNumber: "ABCDE20160426001",
230
- allowancePaperReturned: "Y",
231
- }
232
- ```
149
+ Rescue one class, or all of them:
233
150
 
234
151
  ```ruby
235
- result = client.cancel(payload)
236
- result.successful?
237
- #=> true
152
+ begin
153
+ provider.void(invoice: issued.reference, reason: "customer cancelled")
154
+ rescue Einvoice::ConflictError => e
155
+ # Only :already_voided means that the invoice is voided. Another reason,
156
+ # such as :void_blocked_by_allowance, means that it is not.
157
+ raise unless e.reason == :already_voided
158
+ rescue Einvoice::Error => e
159
+ e.code # => :network, :auth, :not_found, …
160
+ raise
161
+ end
238
162
  ```
239
163
 
240
- ### Search invoice by memberId/sellTargetCode (載具/會員發票查詢)
164
+ The class tells you what to do next, the same way at every provider:
241
165
 
242
- ```ruby
243
- payload = {
244
- companyUn: "12345678",
245
- invoiceStartDate: "20160401",
246
- invoiceEndDate: "20160425",
247
- carrierId: "TP03000001234567",
248
- memberId: "",
249
- sellTargetCode: "",
250
- }
251
- ```
166
+ - `ValidationError`: the input breaks a MIG rule, so no provider takes it. Fix the input.
167
+ - `UnsupportedError`: this provider does not take the input, or does not have the feature. Another provider may take it.
168
+ - `NetworkError`: the request may not have reached the provider. You can retry it. See the table below.
169
+ - `reason: :rate_limited`, on any class: the provider asks you to slow down. Retry later.
170
+ - `ConflictError` with `reason: :retry_later`: the provider is still working on the invoice. Try again later.
252
171
 
253
- ```ruby
254
- result = client.search_invoice_by_member_id(payload)
255
- result.successful?
256
- #=> true
257
- result.data
258
- #=>
259
- # [
260
- # {
261
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
262
- # "invoiceNumber"=>"GX38551078",
263
- # "checkNumber"=>"4229",
264
- # "invoiceDate"=>"20160425",
265
- # "invoiceTime"=>"12:34:58",
266
- # "exclusiveAmount"=>"19048",
267
- # "tax"=>"952",
268
- # "total"=>"20000",
269
- # "status"=>"V",
270
- # "hasAllowance"=>"N",
271
- # "sellerName"=>"Starbucks",
272
- # "sellerUN"=>"12345678",
273
- # "sellerAddr"=>"1 Infinite Loop - Cupertino CA",
274
- # "sellerTel"=>"415-284-0579",
275
- # "receiverName"=>"John Appleseed",
276
- # "receiverAddr"=>"1 Infinite Loop - Cupertino CA",
277
- # "paper"=>"N",
278
- # "win"=>"N",
279
- # "donate"=>"N",
280
- # "carrierType"=>"CQ0001",
281
- # "carrierId"=>"TP03000001234567"
282
- # }
283
- # ]
284
- ```
172
+ After a timeout, the first request may have gone through:
173
+
174
+ | Operation | Retry? | How you know the first one went through |
175
+ | --- | --- | --- |
176
+ | `issue` | Yes, with the same `order_id` | `ConflictError` with `reason: :duplicate_order` |
177
+ | `void`, `void_allowance` | Yes. Nothing can be voided twice | `ConflictError` with `reason: :already_voided` |
178
+ | `allowance` at Amego | Yes, with the same `allowance_id` | Amego refuses a second one with `reason: :duplicate_allowance` |
179
+ | `allowance` at ECPay or ezPay | Check first | The provider assigns the allowance number, so the adapter cannot find it. Check the provider's back office |
180
+ | `allowance` at Tradevan | Check first | Tradevan takes `allowance_id`, but nobody has checked whether it refuses a repeat |
181
+
182
+ ### Credentials and buyer data
285
183
 
286
- ### Search invoice detail (發票開立明細查詢)
184
+ - `inspect`, `to_s` and `pp` show a result's `raw` as `[FILTERED]`, because `raw` is the provider's response and holds the buyer's data. Read `#raw` directly when you need it.
185
+ - A `Buyer` shows its name, email, address and phone as `[FILTERED]` too, in every input and result. Its `ubn` stays.
186
+ - An adapter's client shows its keys as `[FILTERED]`.
187
+ - `base_url` has to use https. Only localhost may use http, for tests. It must not carry a user, a password, a query or a fragment.
188
+
189
+ ### Capabilities
190
+
191
+ A provider declares what it supports. Check a feature first, so that you do not find a gap only when a request fails.
287
192
 
288
193
  ```ruby
289
- result = client.search_invoice_detail("GX38551078")
290
- result.successful?
291
- #=> true
292
- result.data
293
- #=>
294
- # {
295
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
296
- # "invoiceNumber"=>"GX38551078",
297
- # "checkNumber"=>"4229",
298
- # "invoiceDate"=>"20160425",
299
- # "invoiceTime"=>"12:34:58",
300
- # "exclusiveAmount"=>"19048",
301
- # "tax"=>"952",
302
- # "total"=>"20000",
303
- # "status"=>"I",
304
- # "hasAllowance"=>"N",
305
- # "sellerName"=>"Starbucks",
306
- # "sellerUN"=>"12345678",
307
- # "sellerAddr"=>"1 Infinite Loop - Cupertino CA",
308
- # "sellerTel"=>"415-284-0579",
309
- # "receiverName"=>"John Appleseed",
310
- # "receiverAddr"=>"1 Infinite Loop - Cupertino CA",
311
- # "receiverPhone"=>"415-284-0579",
312
- # "paper"=>"Y",
313
- # "win"=>"N",
314
- # "donate"=>"N",
315
- # "carrierType"=>"CQ0001",
316
- # "detailList"=>[
317
- # {
318
- # "saleIdentifier"=>"12345678_ABCDE_53b2a44e4b3c",
319
- # "serialNumber"=>"0001",
320
- # "productName"=>"Coffee Latte",
321
- # "qty"=>"4000",
322
- # "price"=>"5",
323
- # "total"=>"20000",
324
- # "taxType"=>"T"
325
- # }
326
- # ]
327
- # }
194
+ provider.supports?(Einvoice::Capability::FOREIGN_CURRENCY) # => true / false
195
+ provider.assert_supports!(Einvoice::Capability::B2B) # raises UnsupportedError if absent
196
+ provider.query_statuses # => the statuses that query can return
328
197
  ```
329
198
 
330
- ### Send card info to customer (電子發票載具歸戶/中獎通知作業)
199
+ [Providers at a glance](#providers-at-a-glance) shows what each provider declares.
200
+
201
+ ## Provider notes
202
+
203
+ Everything above works the same at every provider. `issue`, `void`, `allowance`, `void_allowance` and `query` take the same unified input and return the same value types. Each section below lists only what differs.
204
+
205
+ ### ECPay 綠界
331
206
 
332
207
  ```ruby
333
- payload = {
334
- companyUn: "12345678",
335
- sellTargetCode: "xxx",
336
- invoiceStartYM: "201604",
337
- invoiceEndYM: "201604",
338
- receiverEmail: "john@gmail.com",
339
- receiverMobile: "",
340
- }
208
+ require "einvoice/ecpay"
209
+
210
+ provider = Einvoice::ECPay::Provider.new(
211
+ merchant_id: "2000132",
212
+ hash_key: "...", # 16 bytes, server-side only
213
+ hash_iv: "...", # 16 bytes, server-side only
214
+ mode: :production # :test (default) targets the stage host
215
+ )
341
216
  ```
342
217
 
218
+ To try it without an account, use ECPay's published test credentials. Every developer shares them, so never use them for anything real:
219
+
343
220
  ```ruby
344
- result = client.send_card_info_to_cust(payload)
345
- result.successful?
346
- #=> true
347
- result.data
221
+ provider = Einvoice::ECPay::Provider.new(**Einvoice::ECPay::SANDBOX)
348
222
  ```
349
223
 
350
- ### Get invoice mark info (電子發票字軌號碼配額取號/分配作業)
224
+ - **The adapter decides paper or electronic.** An invoice with a carrier or a donation is electronic (`Print=0`). Anything else prints, and ECPay then requires a buyer name, an address, and an email or a phone.
225
+ - **Void, allowance and a query by number need the invoice's issue date.** It comes from `invoice.invoice_datetime`. If the reference has an `order_id` instead, a query goes by order id, and a void or an allowance looks the date up first. A failed lookup raises `ProviderError` with `reason: :lookup_failed`. A plain number is not enough.
226
+ - **Void allowance needs the invoice number**, so pass the `AllowanceReference`, not only the allowance number.
227
+ - **Carrier validation**: `validate_carrier({ type: "MOBILE_BARCODE", code: "/ABC1234" })` asks ECPay whether a mobile barcode is registered. `validate_love_code("168001")` and `love_code_organ_name("168001")` check a 愛心碼. These ask ECPay, so they need this adapter and its credentials. `Einvoice::MOF::DonationCodes` ([below](#財政部-lookups)) checks a 愛心碼 at 財政部 and needs neither.
228
+ - **Anything else**: ECPay has about 25 more B2C endpoints, such as 延遲開立, 字軌設定, 列印 and 通知. Reach them through `provider.raw(path, payload)`. It applies the envelope, the encryption and the error mapping for you.
229
+ - The details and the open questions are in [`docs/providers/ecpay/b2c.md`](docs/providers/ecpay/b2c.md).
230
+
231
+ ### Amego 光貿
351
232
 
352
233
  ```ruby
353
- payload = {
354
- companyUn: "12345678",
355
- orgId: "ABCDE",
356
- uniFiedNumber: "12345678",
357
- bookType: "API",
358
- period: "201604",
359
- }
234
+ require "einvoice/amego"
235
+
236
+ provider = Einvoice::Amego::Provider.new(
237
+ ban: "12345678", # the seller's 統一編號
238
+ app_key: "..." # from Amego support, server-side only
239
+ )
360
240
  ```
361
241
 
242
+ To try it without an account, use Amego's published test account. Every developer shares it, so never use it for anything real:
243
+
362
244
  ```ruby
363
- result = client.get_invoice_mark_info(payload)
364
- result.successful?
365
- #=> true
366
- result.data
367
- #=>
368
- # [
369
- # {
370
- # "unifiedNumber"=>"12345678",
371
- # "bookNumber"=>"API_M1",
372
- # "bookType"=>"API",
373
- # "period"=>"201604",
374
- # "duration"=>"201604",
375
- # "mark"=>"GX",
376
- # "start"=>"38551050",
377
- # "end"=>"38551249"
378
- # }
379
- # ]
245
+ provider = Einvoice::Amego::Provider.new(**Einvoice::Amego::SANDBOX)
380
246
  ```
381
247
 
382
- ### Get donate unit list (受贈機關/社福團體愛心碼清單查詢)
248
+ Amego has one host for test and production. The account decides which one you use.
249
+
250
+ - **Amego picks the invoice number** (自動配號).
251
+ - **A void is queued.** Amego accepts it at once, but a query right after it can still report the invoice as issued.
252
+ - **An allowance needs the original invoice's buyer and date.** The reference has the date and the 統一編號, but not the buyer's name, so the adapter queries the invoice for it. To skip the query, pass `provider_options: { buyer_name: }`, for example for an invoice older than 180 days. The allowance date is today (Asia/Taipei).
253
+ - **The allowance number is yours.** The adapter sends `allowance_id` as Amego's `AllowanceNumber`: at most 16 characters, and unique in the account.
254
+ - **Carrier validation**: `validate_carrier({ type: "MOBILE_BARCODE", code: "/ABC1234" })` asks Amego whether a mobile barcode is registered. For a 愛心碼, use `Einvoice::MOF::DonationCodes` ([below](#財政部-lookups)).
255
+ - **Anything else**: reach the other endpoints through `provider.raw(path, payload)`. Section 3 of the note lists them.
256
+ - The details and the open questions are in [`docs/providers/amego/api.md`](docs/providers/amego/api.md).
257
+
258
+ ### ezPay 簡單行動支付 (experimental)
383
259
 
384
260
  ```ruby
385
- client.get_donate_unit_list("12345678")
261
+ require "einvoice/ezpay"
262
+
263
+ provider = Einvoice::EzPay::Provider.new(
264
+ merchant_id: "...", # 商店代號
265
+ hash_key: "...", hash_iv: "...", # 32 and 16 bytes, server-side only
266
+ mode: :test # or :production
267
+ )
386
268
  ```
387
269
 
388
- ### Get invoice content (電子發票內容查詢)
270
+ - **Experimental.** ezPay has no shared test account, and nobody has run this adapter against ezPay. Its encryption and `CheckCode` match the samples in ezPay's manual byte for byte. Test it against your own test shop before you rely on it.
271
+ - **A query needs the random code.** The reference from `issue` or `query` has it.
272
+ - **An allowance needs the invoice's order id.** The reference has it. Without it, the adapter queries the invoice by number first. ezPay assigns the allowance number, so the adapter does not send `allowance_id`. The allowance date is today (Asia/Taipei).
273
+ - **A query cannot tell an allowance.** ezPay only says if an invoice is voided. An invoice that is not voided reads back with status `nil`.
274
+ - **A void waits for the upload.** ezPay uploads the day's invoices the next morning, and refuses a void before that.
275
+ - **Prices follow the category.** ezPay wants B2C prices with tax and B2B prices without. The adapter takes them from the core's breakdown, so any `price_mode` works. Item counts and unit prices must be whole numbers.
276
+ - **Anything else**: `provider.raw(path, version, fields)`, for example `provider.raw("/Api/invoice_touch_issue", "1.0", { ... })`.
277
+ - The details and the open questions are in [`docs/providers/ezpay/invoice.md`](docs/providers/ezpay/invoice.md).
278
+
279
+ ### Tradevan 關貿 (DEFAULTAPI, experimental)
389
280
 
390
281
  ```ruby
391
- payload = {
392
- invoiceNumber: "GX38551078",
393
- sellTargetCode: "",
394
- invoiceStartDate: "",
395
- invoiceEndDate: "",
396
- }
282
+ require "einvoice/tradevan"
283
+
284
+ provider = Einvoice::Tradevan::DefaultAPI::Provider.new(
285
+ acnt: "...", acntp: "...",
286
+ key1: "...", key2: "...", # 16 bytes each, server-side only
287
+ base_url: "https://...", # your Tradevan host; there is no default
288
+ company_un: "12345678", org_id: "ABCDE",
289
+ paper_print_mode: "0", invoice_alarm_mode: "4",
290
+ invoice_paper_returned: "N", allowance_paper_returned: "N",
291
+ member_carrier_type: "1K0001" # only needed for MEMBER carriers
292
+ )
397
293
  ```
398
294
 
295
+ - **Experimental.** This adapter is ported from the 1.x client, its validators and its README examples. Tradevan does not publish its API docs, and nobody has run this adapter against the live API. Test it against your own account before you rely on it. The 1.x client stays on `1-x-stable`.
296
+ - **Void and allowance need the original `saleIdentifier`.** DEFAULTAPI identifies an invoice by it. The adapter takes it from `provider_options: { sale_identifier: }` first. Use this for an invoice that the 1.x client issued. Otherwise it builds the identifier from the reference's order id, or else queries the invoice by number. An allowance also needs the invoice date, from the reference or the same query. The reference from `issue` has all of these.
297
+ - **An allowance needs the tax type and rate** before any lookup. They come from the reference of `issue` or `query`. With only an invoice number, pass `tax_type:` and, for taxable items, `tax_rate:` in the allowance input.
298
+ - **Query status is often `nil`.** Nobody knows what DEFAULTAPI's status codes mean, so the adapter does not guess. `status` is `:allowance` when the invoice has an allowance, and `nil` otherwise. The raw code is in `result.raw["status"]`.
299
+ - **Prices include tax on the wire.** The adapter takes them from the core's breakdown, so any `price_mode` works. When the allowance response has no date, the allowance date is today (Asia/Taipei).
300
+ - **Anything else**: reach the other DEFAULTAPI endpoints through `provider.raw(path, params)`, for example `provider.raw("get/getInvoiceMarkInfo", { ... })`.
301
+ - The details and the open questions are in [`docs/providers/tradevan/defaultapi.md`](docs/providers/tradevan/defaultapi.md).
302
+
303
+ ## Input rules
304
+
305
+ The core checks these rules before any request, so every provider gives the same answer. A broken rule raises `ValidationError`.
306
+
307
+ - A buyer `ubn` is 8 digits, a company's 統一編號. A B2B invoice needs one, and an explicit `category` has to agree with it.
308
+ - Totals are whole numbers and not negative. Item quantity, price and amount are numbers with at most 7 decimal places. An invoice item may be negative, as a discount line. An allowance item may not (MIG 4.1), and its amount is whole TWD (MIG G0401).
309
+ - A number can be an `Integer`, a `BigDecimal`, a `Rational`, a `Float` or a numeric string such as `"100"` or `"0.05"`. A `Float` is read through its shortest form, so `0.1` stays `0.1`.
310
+ - A mobile barcode is `/` and 7 characters. A citizen certificate is 2 letters and 14 digits. These formats come from the providers' docs, because the MIG lists only the carrier types. A 愛心碼 is 3 to 7 digits. The MIG also takes the recipient's 統一編號 in that field. But at the time of sale, the buyer gives a 愛心碼, so the core takes only that form.
311
+ - `tax_rate` is a decimal, such as `0.05`, and has to be a MIG rate. On an issue, the lines decide its default, not the header: `0.05` when a line is taxable, else `0`. A special-tax line needs a rate. A taxable line takes the general rate `0.05` only (營業稅法第 10 條). The other rates are for special tax.
312
+ - A zero-rated invoice needs `customs_clearance_mark`, `"1"` or `"2"` (MIG CustomsClearanceMark). It also needs `zero_tax_rate_reason`, `"71"` to `"79"` (MIG ZeroTaxRateReason).
313
+ - The amounts agree with the items ([Amounts and tax](#amounts-and-tax)).
314
+ - The MIG field lengths: `remark` 200, buyer `name` 60, `address` 100, `email` 400, `phone` 26, carrier `code` 400, item `description` 500, `unit` 6 and `remark` 120. A consumer's name must not be `0` to `0000`, and a carrier code must not start or end with a space. A provider with a shorter limit of its own raises `UnsupportedError`.
315
+ - A void reason is at most 20 characters. A void allowance reason defaults to `作廢折讓`.
316
+
317
+ The [unified model](docs/providers/README.md#the-unified-model) explains each rule and its source.
318
+
319
+ ## 財政部 lookups
320
+
321
+ These clients use 財政部's own public services. They issue nothing and need no credentials, so they work with any provider, or before you pick one.
322
+
399
323
  ```ruby
400
- result = client.get_invoice_content(payload)
401
- result.successful?
402
- #=> true
403
- result.data
404
- #=>
324
+ require "einvoice/mof"
325
+
326
+ codes = Einvoice::MOF::DonationCodes.new
327
+
328
+ codes.lookup("2718")
329
+ # => #<data Einvoice::MOF::DonationCode code="2718",
330
+ # name="社團法人台北市喜願協會", short_name="喜願協會",
331
+ # ubn="92000392", city="臺北市">
332
+
333
+ codes.exist?("105") # => false: well-formed, but not registered
334
+ codes.for_ubn("92000392") # => every 愛心碼 that organisation holds
335
+ codes.all # => the whole dataset (~2,000, five requests)
405
336
  ```
406
337
 
338
+ `Input` does **not** call this client, on purpose. `Input` checks locally, and issuing an invoice must never depend on a third party being reachable. `Input` checks the shape of a 愛心碼. Whether the code is *registered* is a question you ask when it suits you: at order time, or once at boot through `#all`, to build your own set for offline checks.
339
+
340
+ The dataset needs no credentials today. But its published OpenAPI declares `api_key` and `oauth2` schemes. So a 401 or 403 raises `Einvoice::AuthError` that says so, and not a parse failure.
341
+
407
342
  ## Development
408
343
 
409
- After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
344
+ ```bash
345
+ bin/setup # install dependencies
346
+ bundle exec rspec # run the specs
347
+ bundle exec rake # default task: rspec
348
+ ```
349
+
350
+ The shared examples in `spec/support/shared_examples/` are the executable contract. Every adapter runs `"an invoice provider"`, and every adapter's client runs `"a provider client"`. So a new adapter proves that it follows the unified model by including them. A new adapter also gets its own entry file, `lib/einvoice/<name>.rb`, that requires `einvoice`. `lib/einvoice.rb` does not load it, and `spec/spec_helper.rb` does.
351
+
352
+ To write a new adapter, start with the provider notes in [`docs/providers/`](docs/providers/README.md). Read them in this order:
410
353
 
411
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
354
+ 1. the 財政部 MIG note, the standard that every provider follows
355
+ 2. the ECPay note, the first adapter, to see how a note maps to code
356
+ 3. the note for your provider
357
+ 4. the shared examples above
412
358
 
413
- ## Contributing
359
+ The ECPay adapter is tested in three layers. Two of them run offline in CI:
414
360
 
415
- Bug reports and pull requests are welcome on GitHub at https://github.com/abookyun/einvoice.
361
+ 1. **The contract, against a wire-format fake.** The shared examples run through an in-process fake that speaks the real protocol: the AES envelope, PHP url-encoding and ECPay's own RtnCodes. So a request passes only if the encryption and the field mapping are correct. The fake keeps state, so the contract can run issue, allowance and void in order.
362
+ 2. **Recorded real responses (VCR).** `spec/einvoice/ecpay/recorded_spec.rb` replays cassettes from ECPay's stage host. So the field names, value types and error codes under test are ECPay's own, not our reading of the docs. To record again, raise the epoch in that spec, then run with `VCR_RECORD=1`. Cassettes only ever hold sandbox traffic.
363
+ 3. **The live API, opt-in.** It keeps the other two honest:
416
364
 
365
+ ```bash
366
+ ECPAY_LIVE=1 bundle exec rspec spec/einvoice/ecpay/live_spec.rb
367
+ ```
368
+
369
+ It uses the public sandbox credentials by default, so it needs no setup. To use your own stage account, set `ECPAY_MERCHANT_ID`, `ECPAY_HASH_KEY` and `ECPAY_HASH_IV`. CI does not run it, because it needs the network and a shared sandbox.
370
+
371
+ Amego has a live spec too. It runs against Amego's public test account:
372
+
373
+ ```bash
374
+ AMEGO_LIVE=1 bundle exec rspec spec/einvoice/amego/live_spec.rb
375
+ ```
417
376
 
418
377
  ## License
419
378