fiscalisto 0.1.225

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 33f27c9cb2fdc9bc20c82c2e16e159638ad0b43214703bfea25ef1715c12ac87
4
+ data.tar.gz: d51d7d15c4ed36397d6bf3455573271d7f31f300db1953825efb34a616b2a9e1
5
+ SHA512:
6
+ metadata.gz: 4d9aea057a3a96cbcd210fe9361ea85788994f57fafe81d78d48f39305ace2d658cc2f17d03ed30b2e2018abcf3c29178890ae8d486fca6dfc5916d1991c302b
7
+ data.tar.gz: 39b7e82226a764113fa1718cb6ba99307f66308287bf5d9fe6bd25540b77e6a6f65775d30abdbede0ef7d3bae7b150846a234ad9808e89361065cf3130c6ed9f
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fiscalisto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # fiscalisto
2
+
3
+ El SDK de la [API de facturación de Fiscalisto](https://fiscalisto.com/docs/api): timbre CFDI 4.0 (facturas, pagos, notas de crédito, nómina, retenciones y lotes) desde Ruby.
4
+
5
+ - `Idempotency-Key` automática en cada `POST` que timbra o crea: un reintento nunca timbra, crea ni manda nada dos veces.
6
+ - Reintentos solo de lo que es seguro repetir, con espera creciente y respetando `Retry-After`.
7
+ - Errores con su clase (`Fiscalisto::InvoiceError`, `Fiscalisto::RateLimitError`…), su `code`, `param`, `request_id` y `request_log_url`.
8
+ - Listas que se recorren solas con `each` (y `map`, `select`, `first(50)`…).
9
+ - `expand` para traer el objeto en lugar de su id.
10
+ - Webhooks verificados en una línea.
11
+ - Sin dependencias: Ruby 3.1 o más reciente.
12
+
13
+ ```bash
14
+ gem install fiscalisto
15
+ ```
16
+
17
+ ```ruby
18
+ require "fiscalisto"
19
+
20
+ fiscalisto = Fiscalisto::Client.new # la llave viene de FISCALISTO_API_KEY
21
+
22
+ invoice = fiscalisto.invoices.create(
23
+ {
24
+ customer: { tax_id: "ICV060329BY0", legal_name: "INMOBILIARIA CVA", tax_system: "601", zip: "33826" },
25
+ payment_form: "03",
26
+ items: [{ description: "Mensualidad", product_key: "86121700", quantity: 2, unit_price: 2500 }]
27
+ },
28
+ idempotency_key: "pedido-A-1042"
29
+ )
30
+
31
+ puts invoice.uuid, invoice.total
32
+ ```
33
+
34
+ Cada respuesta se lee como método (`invoice.uuid`) o como Hash (`invoice[:uuid]`). Las opciones de una llamada (`idempotency_key`, `timeout`, `max_retries`, `expand`) van al final, como palabras clave o en un segundo Hash; las demás palabras clave son los parámetros:
35
+
36
+ ```ruby
37
+ fiscalisto.invoices.list(status: "valid").each { |inv| puts inv.uuid }
38
+
39
+ invoice = fiscalisto.invoices.get("inv_…", expand: ["issuer"])
40
+ puts invoice.issuer.legal_name
41
+
42
+ begin
43
+ fiscalisto.invoices.create(params)
44
+ rescue Fiscalisto::InvoiceError => e
45
+ puts e.code, e.param, e.request_log_url
46
+ end
47
+ ```
48
+
49
+ Webhooks (Rails: `request.raw_post` y `request.headers`; Rack o Sinatra: `request.body.read` y `request.env`):
50
+
51
+ ```ruby
52
+ event = Fiscalisto::Webhook.verify(request.raw_post, request.headers, ENV["FISCALISTO_WEBHOOK_SECRET"])
53
+ puts event.data.object.uuid if event.type == "invoice.stamped"
54
+ ```
55
+
56
+ La guía completa está en [fiscalisto.com/docs/api/sdk](https://fiscalisto.com/docs/api/sdk) y cada página de la [referencia](https://fiscalisto.com/docs/api) trae su ejemplo con el SDK.
57
+
58
+ ## Con agentes de IA
59
+
60
+ Para que Claude Code, Cursor, Codex u otro agente integre Fiscalisto, conecte el servidor MCP de la documentación (sin llave) y pídale que empiece con `get_started`:
61
+
62
+ ```bash
63
+ claude mcp add --transport http fiscalisto-docs https://fiscalisto.com/docs/api/mcp
64
+ ```
65
+
66
+ La guía de integración en una página está en [fiscalisto.com/docs/api/SKILL.md](https://fiscalisto.com/docs/api/SKILL.md) y el índice de la documentación para agentes en [llms.txt](https://fiscalisto.com/docs/api/llms.txt). Otros clientes y más: [fiscalisto.com/docs/api/agentes](https://fiscalisto.com/docs/api/agentes).
67
+
68
+ ## Desarrollo
69
+
70
+ `lib/fiscalisto/resources.rb` y `lib/fiscalisto/error_codes.rb` se generan desde la especificación OpenAPI con `bun run openapi` en la raíz del repositorio; no los edite. Lo demás se escribe a mano.
71
+
72
+ ```bash
73
+ ruby -w -Ilib -Itest test/test_fiscalisto.rb # o: bundle exec rake
74
+ gem build fiscalisto.gemspec
75
+ ```
@@ -0,0 +1,363 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "securerandom"
7
+ require "time"
8
+ require "uri"
9
+
10
+ module Fiscalisto
11
+ DEFAULT_BASE_URL = "https://api.fiscalisto.com"
12
+
13
+ # Lo que el SDK manda (para un transport propio).
14
+ HttpRequest = Struct.new(:method, :url, :headers, :body, :timeout, keyword_init: true)
15
+ # Lo que el transport contesta: headers con nombres en minúsculas.
16
+ HttpResponse = Struct.new(:status, :headers, :body, keyword_init: true)
17
+
18
+ # Lo que un transport lanza cuando no hubo respuesta: el SDK reintenta lo que es seguro
19
+ # repetir y, al final, lanza APIConnectionError.
20
+ CONNECTION_ERRORS = [
21
+ IOError, EOFError, SystemCallError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError
22
+ ].freeze
23
+
24
+ # El transport de siempre: Net::HTTP de la biblioteca estándar, con la conexión abierta entre
25
+ # una solicitud y la siguiente (keep-alive), una por hilo y por servidor. Otro transport es
26
+ # cualquier objeto con call(HttpRequest) → HttpResponse (pruebas, proxies, otro cliente HTTP).
27
+ class NetHttpTransport
28
+ # Seconds an idle connection is reused; after that Net::HTTP opens a new one before sending.
29
+ KEEP_ALIVE = 10
30
+
31
+ def call(request)
32
+ uri = URI(request.url)
33
+ http = connection(uri)
34
+ http.open_timeout = [request.timeout, 30].min
35
+ http.read_timeout = request.timeout
36
+ http.write_timeout = request.timeout
37
+ klass = Net::HTTP.const_get(request[:method].capitalize)
38
+ req = klass.new(uri.request_uri)
39
+ request.headers.each { |k, v| req[k] = v }
40
+ req.body = request.body if request.body
41
+ begin
42
+ res = http.request(req)
43
+ rescue *CONNECTION_ERRORS
44
+ # A connection that failed isn't used again: the next request (a retry) opens another.
45
+ forget(uri)
46
+ raise
47
+ end
48
+ headers = {}
49
+ res.each_header { |k, v| headers[k.downcase] = v }
50
+ HttpResponse.new(status: res.code.to_i, headers: headers, body: res.body.to_s)
51
+ end
52
+
53
+ # Closes this thread's open connections.
54
+ def close
55
+ pool.each_value { |http| http.finish if http.started? }
56
+ pool.clear
57
+ end
58
+
59
+ private
60
+
61
+ # Per thread (Net::HTTP isn't safe to share) and per process (a fork doesn't reuse the
62
+ # parent's sockets).
63
+ def pool
64
+ key = :"fiscalisto_http_#{object_id}"
65
+ held = Thread.current[key]
66
+ held = Thread.current[key] = { pid: Process.pid, connections: {} } if held.nil? || held[:pid] != Process.pid
67
+ held[:connections]
68
+ end
69
+
70
+ def connection(uri)
71
+ origin = "#{uri.scheme}://#{uri.host}:#{uri.port}"
72
+ http = pool[origin]
73
+ return http if http&.started?
74
+
75
+ http = Net::HTTP.new(uri.host, uri.port)
76
+ http.use_ssl = uri.scheme == "https"
77
+ http.keep_alive_timeout = KEEP_ALIVE
78
+ http.open_timeout = 30
79
+ http.start
80
+ pool[origin] = http
81
+ end
82
+
83
+ def forget(uri)
84
+ http = pool.delete("#{uri.scheme}://#{uri.host}:#{uri.port}")
85
+ http.finish if http&.started?
86
+ rescue IOError
87
+ nil
88
+ end
89
+ end
90
+
91
+ NET_HTTP_TRANSPORT = NetHttpTransport.new
92
+
93
+ # La llave, la dirección de la API, los reintentos y el transport. Los recursos
94
+ # (resources.rb, generado) solo dicen qué ruta llamar.
95
+ class Core
96
+ KEY = /\Afk_(live|test)_/.freeze
97
+ OPTIONS = %i[idempotency_key timeout max_retries expand].freeze
98
+
99
+ # api_key: su llave fk_test_… o fk_live_…; sin ella, la variable FISCALISTO_API_KEY.
100
+ # timeout: segundos para cada respuesta (80 por omisión: el PAC puede tardar).
101
+ # api_version: la versión de la API (Fiscalisto-Version); nil usa la de su cuenta.
102
+ # language: "en" para los mensajes de error en inglés (Accept-Language).
103
+ # transport: otro cliente HTTP (vea NET_HTTP_TRANSPORT); sleep: cómo esperar entre reintentos.
104
+ # warn: cómo avisar que la llave vence pronto (Kernel.warn por omisión), una vez por cliente.
105
+ def initialize(api_key = nil, base_url: nil, max_retries: 2, timeout: 80, transport: nil,
106
+ sleep: nil, api_version: API_VERSION, language: nil, warn: nil)
107
+ key = api_key || ENV.fetch("FISCALISTO_API_KEY", nil)
108
+ if key.nil? || key.empty?
109
+ raise ArgumentError,
110
+ 'Falta la llave de la API: Fiscalisto::Client.new("fk_test_…") o la variable ' \
111
+ "FISCALISTO_API_KEY. Créela en Desarrolladores › Llaves."
112
+ end
113
+ unless KEY.match?(key)
114
+ raise ArgumentError,
115
+ "La llave de la API empieza con fk_live_ o fk_test_. (Un secreto whsec_ es " \
116
+ "para verificar webhooks.)"
117
+ end
118
+
119
+ @api_key = key
120
+ # A proxy's path stays: https://proxy.example.com/fiscalisto + /v1/invoices.
121
+ @base_url = (base_url || DEFAULT_BASE_URL).sub(%r{/+\z}, "")
122
+ @max_retries = max_retries
123
+ @timeout = timeout
124
+ @transport = transport || NET_HTTP_TRANSPORT
125
+ @sleep = sleep || ->(seconds) { Kernel.sleep(seconds) }
126
+ @api_version = api_version
127
+ @language = language
128
+ @warn = warn || ->(message) { Kernel.warn(message) }
129
+ @warned_expiry = false
130
+ end
131
+
132
+ WEEK = 7 * 24 * 60 * 60
133
+
134
+ # The key's end, when the API says it's near (Fiscalisto-Key-Expires-At within 7 days, or
135
+ # Fiscalisto-Warning: api_key_expires_soon): a message for the console, nil otherwise.
136
+ def self.expiry_warning(headers, now = Time.now)
137
+ expires_at = headers["fiscalisto-key-expires-at"].to_s
138
+ at = begin
139
+ Time.iso8601(expires_at)
140
+ rescue ArgumentError
141
+ nil
142
+ end
143
+ flagged = /\bapi_key_expires_soon\b/.match?(headers["fiscalisto-warning"].to_s)
144
+ return nil unless flagged || (at && at > now && at - now <= WEEK)
145
+
146
+ when_ = at ? "el #{at.utc.strftime("%Y-%m-%dT%H:%M:%SZ")}" : "en menos de 7 días"
147
+ "[fiscalisto] Su llave de la API vence #{when_}. Cámbiela antes en Desarrolladores › " \
148
+ "Llaves (Cambiar llave) para que sus solicitudes no fallen con api_key_expired."
149
+ end
150
+
151
+ # true con una llave fk_live_ (producción), false con fk_test_ (pruebas).
152
+ def livemode?
153
+ @api_key.start_with?("fk_live_")
154
+ end
155
+ alias livemode livemode?
156
+
157
+ def inspect
158
+ "#<#{self.class.name} base_url=#{@base_url.inspect} livemode=#{livemode?}>"
159
+ end
160
+
161
+ # Una llamada: method "GET"/"POST"/"DELETE", path "/v1/…". body o query son los params;
162
+ # result :json (un FiscalistoObject), :bytes o :text. opts: idempotency_key, timeout,
163
+ # max_retries, expand.
164
+ def execute_request(method, path, body: nil, query: nil, idempotent: false, result: :json, opts: {})
165
+ opts = check_options(opts, idempotent)
166
+ body, query, expand = split_expand(body, query, opts[:expand])
167
+ url = @base_url + path
168
+ pairs = query_pairs(query)
169
+ # Ids as their objects in the same answer: expand: ["issuer", "data.recurring_invoice"].
170
+ expand.each { |field| pairs << ["expand[]", field.to_s] }
171
+ url = "#{url}?#{URI.encode_www_form(pairs)}" unless pairs.empty?
172
+
173
+ headers = {
174
+ "authorization" => "Bearer #{@api_key}",
175
+ "user-agent" => "fiscalisto-ruby/#{VERSION} ruby/#{RUBY_VERSION}",
176
+ "accept" => "application/json"
177
+ }
178
+ headers["fiscalisto-version"] = @api_version if @api_version
179
+ headers["accept-language"] = @language if @language
180
+ key = idempotent ? (opts[:idempotency_key] || SecureRandom.uuid) : nil
181
+ headers["idempotency-key"] = key if key
182
+ data = nil
183
+ if method == "POST"
184
+ headers["content-type"] = "application/json"
185
+ data = JSON.generate(body.nil? ? {} : body)
186
+ end
187
+ # Only what can't do something twice is repeated after a failure we can't see through:
188
+ # reads, deletes and requests with an Idempotency-Key. A 429 was never processed.
189
+ safe = %w[GET DELETE].include?(method) || !key.nil?
190
+ retries = opts[:max_retries] || @max_retries
191
+ wait = opts[:timeout] || @timeout
192
+
193
+ attempt = 0
194
+ loop do
195
+ begin
196
+ res = @transport.call(HttpRequest.new(method: method, url: url, headers: headers.dup,
197
+ body: data, timeout: wait))
198
+ rescue *CONNECTION_ERRORS => e
199
+ if safe && attempt < retries
200
+ @sleep.call(backoff(attempt))
201
+ attempt += 1
202
+ next
203
+ end
204
+ raise connection_error(e, key, wait)
205
+ end
206
+ request_id = res.headers["request-id"]
207
+ unless @warned_expiry
208
+ warning = Core.expiry_warning(res.headers)
209
+ if warning
210
+ @warned_expiry = true
211
+ @warn.call(warning)
212
+ end
213
+ end
214
+ if res.status >= 200 && res.status < 300
215
+ return answer(res, result, request_id)
216
+ end
217
+
218
+ raw = error_body(res.body)
219
+ # Retry-After when the API sends it; otherwise RateLimit-Reset on a 429 (seconds until
220
+ # the next request fits).
221
+ wait_header = res.headers["retry-after"] || (res.status == 429 ? res.headers["ratelimit-reset"] : nil)
222
+ retry_after = Float(wait_header || "", exception: false) || 0.0
223
+ retryable = res.status == 429 || raw["code"] == "request_in_progress" || (safe && res.status >= 500)
224
+ if retryable && attempt < retries && retry_after <= 60
225
+ @sleep.call(retry_after.positive? ? retry_after : backoff(attempt))
226
+ attempt += 1
227
+ next
228
+ end
229
+ raise Error.for(raw, res.status, request_id, key)
230
+ end
231
+ end
232
+
233
+ # Una lista que se recorre sola (ListObject): cada página con los mismos params.
234
+ def execute_list(path, params, opts: {})
235
+ opts = check_options(opts, false)
236
+ _, query, expand = split_expand(nil, params, opts[:expand])
237
+ query = (query || {}).to_h.transform_keys(&:to_s)
238
+ forward = !query["ending_before"].to_s.empty?
239
+ page = lambda do |cursor|
240
+ q = query.dup
241
+ q[forward ? "ending_before" : "starting_after"] = cursor if cursor
242
+ execute_request("GET", path, query: q, opts: opts.merge(expand: expand))
243
+ end
244
+ ListObject.new(page, forward: forward)
245
+ end
246
+
247
+ # What resources.rb calls: params (a Hash), opts (a Hash) and keywords, where a keyword
248
+ # that is an option (idempotency_key, timeout, max_retries, expand) is one and any other
249
+ # is a param: create({ … }, idempotency_key: "x") and list(status: "valid") both work.
250
+ def call(method, path, params, opts, kw, send: nil, idempotent: false, result: :json)
251
+ params, opts = arguments(params, opts, kw)
252
+ execute_request(method, path, body: send == :body ? params : nil,
253
+ query: send == :query ? params : nil,
254
+ idempotent: idempotent, result: result, opts: opts)
255
+ end
256
+
257
+ def list_call(path, params, opts, kw)
258
+ params, opts = arguments(params, opts, kw)
259
+ execute_list(path, params, opts: opts)
260
+ end
261
+
262
+ # Un pedazo de la ruta (un id, un RFC, un UUID), escapado.
263
+ def self.path(value)
264
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
265
+ end
266
+
267
+ private
268
+
269
+ def arguments(params, opts, kw)
270
+ options = (opts || {}).to_h.transform_keys(&:to_sym)
271
+ rest = {}
272
+ kw.each { |k, v| OPTIONS.include?(k.to_sym) ? options[k.to_sym] = v : rest[k] = v }
273
+ unless params.nil? || params.is_a?(Hash) || params.respond_to?(:to_h)
274
+ raise ArgumentError, "Los params van en un Hash: #{params.inspect}."
275
+ end
276
+
277
+ params = params.nil? ? (rest.empty? ? nil : rest) : params.to_h.merge(rest)
278
+ [params, options]
279
+ end
280
+
281
+ def check_options(opts, idempotent)
282
+ opts = (opts || {}).to_h.transform_keys(&:to_sym)
283
+ unknown = opts.keys - OPTIONS
284
+ raise ArgumentError, "Opciones que no existen: #{unknown.join(", ")} (son #{OPTIONS.join(", ")})." unless unknown.empty?
285
+ if opts[:idempotency_key] && !idempotent
286
+ raise ArgumentError, "Esta llamada no usa Idempotency-Key: repetirla no hace nada dos veces."
287
+ end
288
+
289
+ opts
290
+ end
291
+
292
+ # expand can also go in the params, as in Stripe: get("inv_…", expand: ["issuer"]).
293
+ def split_expand(body, query, expand)
294
+ fields = Array(expand).dup
295
+ take = lambda do |params|
296
+ next params unless params.is_a?(Hash) && (params.key?(:expand) || params.key?("expand"))
297
+
298
+ params = params.dup
299
+ fields.concat(Array(params.delete(:expand)), Array(params.delete("expand")))
300
+ params
301
+ end
302
+ [take.call(body), take.call(query), fields.uniq]
303
+ end
304
+
305
+ def query_pairs(query)
306
+ return [] if query.nil?
307
+
308
+ query.to_h.each_with_object([]) do |(k, v), pairs|
309
+ case v
310
+ when nil then next
311
+ when Array then v.each { |x| pairs << ["#{k}[]", x.to_s] }
312
+ when Hash then v.each { |kk, vv| pairs << ["#{k}[#{kk}]", vv.to_s] unless vv.nil? }
313
+ else pairs << [k.to_s, v.to_s]
314
+ end
315
+ end
316
+ end
317
+
318
+ def answer(res, result, request_id)
319
+ case result
320
+ when :bytes then res.body.to_s.b
321
+ when :text then res.body.to_s.dup.force_encoding(Encoding::UTF_8)
322
+ else
323
+ begin
324
+ raise JSON::ParserError, "vacía" if res.body.to_s.strip.empty?
325
+
326
+ FiscalistoObject.construct(JSON.parse(res.body))
327
+ rescue JSON::ParserError
328
+ raise invalid_response(res, request_id)
329
+ end
330
+ end
331
+ end
332
+
333
+ def error_body(body)
334
+ parsed = JSON.parse(body.to_s)
335
+ parsed.is_a?(Hash) && parsed["error"].is_a?(Hash) ? parsed["error"] : {}
336
+ rescue JSON::ParserError
337
+ {}
338
+ end
339
+
340
+ # A success that isn't the API's JSON: a proxy's or a network portal's page answered instead.
341
+ def invalid_response(res, request_id)
342
+ text = res.body.to_s.dup.force_encoding(Encoding::UTF_8).scrub.split.join(" ")[0, 80]
343
+ text = "vacía" if text.nil? || text.empty?
344
+ Error.for({ "type" => "api_error", "code" => "invalid_response",
345
+ "message" => "La respuesta (#{res.status}) no es de la API: #{text}. ¿Hay un proxy o un portal de por medio?" },
346
+ res.status, request_id)
347
+ end
348
+
349
+ def connection_error(error, key, wait)
350
+ timed_out = error.is_a?(Timeout::Error) || error.message.include?("timed out")
351
+ hint = key ? " Repita con la misma Idempotency-Key (#{key}) para saber si se timbró." : ""
352
+ Error.for({ "type" => "connection_error",
353
+ "code" => timed_out ? "timeout" : "connection_failed",
354
+ "message" => timed_out ? "La API no contestó en #{wait} s.#{hint}" : "No se pudo conectar con la API: #{error.message}",
355
+ "idempotency_key" => key })
356
+ end
357
+
358
+ # 0.5 s, 1 s, 2 s… hasta 8 s, con algo de azar para no llegar todos juntos.
359
+ def backoff(attempt)
360
+ [8.0, 0.5 * (2**attempt)].min * (0.75 + (rand / 2))
361
+ end
362
+ end
363
+ end