tronzap-sdk 1.1.0 → 1.2.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3ffa340c958b0a66217f4c255dc615ebb13c8580730bcd276658be3e7178a991
4
- data.tar.gz: f464a18b56042ae6e74bde0a194fb464a669891edada491cdd86c967089cc094
3
+ metadata.gz: 95551b6b4d331797048d81550bc7118548f59c64bbb3d46deda99fdcb7568790
4
+ data.tar.gz: 57d6bf136386ad894af3faa8b7a048f520e4c3c82e39c8622ce971a8f4ed7b28
5
5
  SHA512:
6
- metadata.gz: 1e98924e7e7b72f4b4dd8d78b62e8591047a5f0e76795244c071e02f9f324bbf6f07c834e02da72839a813317aa7764ac289cc7c413d74f1b247d16c33046af4
7
- data.tar.gz: 9543a6086b456f1a963ccee701add632f0742eb6c39aedab71ada79f6dc96b6cd3be385edba7d38ebfdef0da841f6098ee44812d300279934e7fbdd2f9b31a69
6
+ metadata.gz: 7aa368493a594653c4a39dca2bba537ef8f2c58608fb375b93b099d7ac639934f3bd6a6a96f1caaab22d28934504dea1d2661a7b0adc3d868e4a81d0348d1eb4
7
+ data.tar.gz: 3382112bcaad87611ef1dd468db4d5c35b6eb06249982e8ccec1a101b44f767c042937fe45387e2725277db8589a6262f489b63fa98a6309d2a45eb371bf2432
data/CHANGELOG.md CHANGED
@@ -6,6 +6,34 @@ All notable changes to this project are documented in this file. The format is b
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.2.0] - 2026-11-20
10
+
11
+ ### Added
12
+
13
+ - Bulk energy orders for up to 10 000 addresses: `Client#bulk_calculate`, `#bulk_create`, `#bulk_check`,
14
+ `#get_bulk_history` and `#bulk_report`, with the requests `Requests::BulkItem`, `Requests::BulkCalculate`,
15
+ `Requests::BulkCreate`, `Requests::BulkLookup`, `Requests::BulkReport` and `Requests::BulkHistory`, the results
16
+ `Responses::BulkCalculation`, `Responses::BulkOrder` and `Responses::BulkHistory`, `Models::BulkRejectedRow`,
17
+ `Models::BULK_STATUSES` and `Models::BULK_ROW_STATUSES`. `bulk_report` returns the CSV report as a UTF-8 string.
18
+ - `Client#verify_webhook_signature` checks the `X-Signature` header of the webhook a bulk order sends when it becomes
19
+ final.
20
+ - `ApiError#result`: the `result` the API sends along with an error, as parsed JSON. Until now the SDK dropped it.
21
+ - `BulkPriceChangedError` (code 92) with the new calculation in `#calculation`, and `BulkNoValidItemsError` (code 94)
22
+ with the rejected rows in `#rejected`. Both are `ApiError`s.
23
+ - `ApiError#retry_after` and `HttpError#retry_after`: seconds to wait before retrying, from the `Retry-After` header
24
+ (seconds or an HTTP date) or the `retry_after` field, or `nil` when the server sent neither.
25
+ - The error codes `BULK_NOT_FOUND` (90), `BULK_EXPIRED` (91), `BULK_PRICE_CHANGED` (92), `BULK_TOO_MANY_ITEMS` (93),
26
+ `BULK_NO_VALID_ITEMS` (94), `BULK_RESOURCE_NOT_SUPPORTED` (95), `PAYLOAD_TOO_LARGE` (96) and `RATE_LIMITED` (429).
27
+ - The example program lists bulk orders, calculates one with an invalid row, checks and reports `TRONZAP_BULK_ID`,
28
+ and with purchases allowed starts a one-address bulk order.
29
+
30
+ ### Changed
31
+
32
+ - `retry_after` moved from `RateLimitError` to its base class `HttpError`, so a 503 from `ServerError` carries it
33
+ too. Code that reads it is unchanged, and the body's `retry_after` field is read when the header is missing.
34
+ - The documentation of `RateLimitError`: it is only an HTTP 429 without an API payload, such as one from a proxy. A
35
+ rate limit reported by the API is an `ApiError` with `RATE_LIMITED`, as it always has been.
36
+
9
37
  ## [1.1.0] - 2026-10-09
10
38
 
11
39
  ### Added
@@ -59,6 +87,7 @@ First release of the official Ruby SDK for the [TronZap API](https://docs.tronza
59
87
  - An error hierarchy under `Tronzap::Error` that separates API, HTTP, response and network failures, with the HTTP
60
88
  status, API error code, error key, request ID and raw response body.
61
89
 
62
- [Unreleased]: https://github.com/tron-energy-market/tronzap-sdk-ruby/compare/v1.1.0...HEAD
90
+ [Unreleased]: https://github.com/tron-energy-market/tronzap-sdk-ruby/compare/v1.2.0...HEAD
91
+ [1.2.0]: https://github.com/tron-energy-market/tronzap-sdk-ruby/releases/tag/v1.2.0
63
92
  [1.1.0]: https://github.com/tron-energy-market/tronzap-sdk-ruby/releases/tag/v1.1.0
64
93
  [1.0.0]: https://github.com/tron-energy-market/tronzap-sdk-ruby/releases/tag/v1.0.0
data/README.es.md CHANGED
@@ -190,6 +190,12 @@ bibliotecas HTTP debe traducirlos el adaptador, como en el ejemplo anterior.
190
190
  | `check_subscription(id: nil, external_id: nil)` | `/v1/subscription/check` | Estado de una suscripción, por id o id externo |
191
191
  | `stop_subscription(id: nil, external_id: nil)` | `/v1/subscription/stop` | Detener una suscripción |
192
192
  | `get_subscription_history(page: 1, per_page: 10, status: nil)` | `/v1/subscriptions/history` | Historial paginado de suscripciones |
193
+ | `bulk_calculate(items:, duration: 1)` | `/v1/bulk/calculate` | Validar y calcular las filas de un pedido masivo de energía |
194
+ | `bulk_create(id:, external_id: nil, force: false, max_price_increase: nil, webhook_url: nil)` | `/v1/bulk/create` | Iniciar un pedido masivo a partir de un cálculo |
195
+ | `bulk_check(id: nil, external_id: nil)` | `/v1/bulk/check` | Estado y progreso de un pedido masivo |
196
+ | `get_bulk_history(page: 1, per_page: 10)` | `/v1/bulk/history` | Historial paginado de pedidos masivos |
197
+ | `bulk_report(id: nil, external_id: nil, status: nil)` | `/v1/bulk/report` | Informe por dirección de un pedido masivo, en CSV |
198
+ | `verify_webhook_signature(body, signature)` | — | Comprobar el `X-Signature` del webhook de un pedido masivo |
193
199
 
194
200
  Los métodos con parámetros aceptan argumentos de palabra clave o un objeto de
195
201
  solicitud de `Tronzap::Requests`, así que una solicitud se puede construir, validar
@@ -320,6 +326,57 @@ historial devuelve en su lugar los contadores de uso `transactions_used`,
320
326
  suscripción están en `Tronzap::Models::SUBSCRIPTION_STATUSES`. Una suscripción con
321
327
  límite de transacciones no se puede detener (`CANNOT_STOP_SUBSCRIPTION`).
322
328
 
329
+ ### Pedidos masivos
330
+
331
+ Compra energía para hasta 10 000 direcciones en un solo pedido. `bulk_calculate`
332
+ valida y calcula las filas y devuelve un cálculo válido durante 10 minutos; no se
333
+ cobra nada. Las filas inválidas no hacen fallar la solicitud: se devuelven en
334
+ `rejected` con su número de fila. `bulk_create` inicia el pedido; cada dirección se
335
+ cobra al procesarse, y las direcciones no activadas se omiten sin cobro.
336
+
337
+ Si el precio cambió desde el cálculo, `bulk_create` no inicia el pedido y lanza
338
+ `Tronzap::BulkPriceChangedError` (código `BULK_PRICE_CHANGED`). Su `calculation` es
339
+ el nuevo cálculo: confirma el nuevo total e inícialo con su `id`.
340
+
341
+ ```ruby
342
+ calculation = client.bulk_calculate(items: [
343
+ { address: "TRecipientAddress1", amount: 65000 },
344
+ { address: "TRecipientAddress2", amount: 131000 }
345
+ ])
346
+ calculation.rejected.each { |row| puts "row #{row.row}: #{row.reason}" }
347
+
348
+ begin
349
+ order = client.bulk_create(id: calculation.id, external_id: "order-42",
350
+ webhook_url: "https://example.com/tronzap/bulk")
351
+ rescue Tronzap::BulkPriceChangedError => e
352
+ new_calculation = e.calculation # confirma el nuevo total e inícialo
353
+ order = client.bulk_create(id: new_calculation.id, external_id: "order-42")
354
+ end
355
+
356
+ order = client.bulk_check(external_id: "order-42") # consulta hasta :completed, :partial o :failed
357
+ csv = client.bulk_report(id: order.id) # row,address,amount,status,reason,charged,transaction_id
358
+ history = client.get_bulk_history(page: 1, per_page: 10)
359
+ ```
360
+
361
+ Las filas son `Tronzap::Requests::BulkItem` o hashes con `address` y `amount`. Un
362
+ pedido pasa por los estados de `Tronzap::Models::BULK_STATUSES`; `:completed`,
363
+ `:partial` y `:failed` son finales. `status:` de `bulk_report` acepta uno de
364
+ `Tronzap::Models::BULK_ROW_STATUSES`.
365
+
366
+ Con `webhook_url`, la API envía un `POST` cuando el pedido llega a un estado final.
367
+ Comprueba su cabecera `X-Signature` con el cuerpo sin procesar antes de confiar en
368
+ él, por ejemplo en Sinatra:
369
+
370
+ ```ruby
371
+ post "/tronzap/bulk" do
372
+ body = request.body.read
373
+ halt 401 unless client.verify_webhook_signature(body, request.env["HTTP_X_SIGNATURE"])
374
+
375
+ order = JSON.parse(body) # {"id":"01kb2m5x9qj4v8n3c7d6e5f4g3","external_id":"order-42","status":"partial"}
376
+ 200
377
+ end
378
+ ```
379
+
323
380
  ## Gestión de errores
324
381
 
325
382
  Todo fallo de una llamada a la API es un `Tronzap::Error`. Captura una subclase
@@ -329,7 +386,7 @@ para tratar un tipo concreto de fallo:
329
386
  Tronzap::Error
330
387
  ├── Tronzap::ApiError — la API respondió con un código distinto de cero
331
388
  ├── Tronzap::HttpError — respuesta no 2xx sin payload de la API
332
- │ ├── Tronzap::RateLimitError — HTTP 429
389
+ │ ├── Tronzap::RateLimitError — HTTP 429 sin respuesta de la API
333
390
  │ ├── Tronzap::UnauthorizedError — HTTP 401 o 403
334
391
  │ └── Tronzap::ServerError — HTTP 5xx
335
392
  ├── Tronzap::InvalidResponseError — respuesta 2xx que el SDK no pudo leer
@@ -342,8 +399,7 @@ Tronzap::Error
342
399
  `ApiError`, `HttpError` e `InvalidResponseError` incluyen el estado HTTP
343
400
  (`status`) y el cuerpo de la respuesta sin procesar (`response_body`). `ApiError`
344
401
  incluye además el código de error de la API (`code`), la clave del error
345
- (`error_key`) y el ID de la solicitud (`request_id`). `RateLimitError#retry_after`
346
- contiene el retraso de `Retry-After` en segundos cuando la API lo envía.
402
+ (`error_key`) y el ID de la solicitud (`request_id`).
347
403
 
348
404
  Los argumentos inválidos no son fallos de la API: lanzan `ArgumentError` antes de
349
405
  enviar nada.
@@ -364,8 +420,8 @@ rescue Tronzap::ApiError => e
364
420
  else
365
421
  warn "api error #{e.code}: #{e.message} (request #{e.request_id || "-"})"
366
422
  end
367
- rescue Tronzap::RateLimitError => e
368
- # Espera y reintenta, tras e.retry_after segundos si la API lo envió.
423
+ rescue Tronzap::RateLimitError
424
+ # HTTP 429 sin respuesta de la API, p. ej. de un proxy: espera y reintenta.
369
425
  rescue Tronzap::UnauthorizedError
370
426
  # Token o firma incorrectos.
371
427
  rescue Tronzap::TimeoutError, Tronzap::ServerError
@@ -383,6 +439,24 @@ algunos fallos con estado 2xx y de otros con 4xx o 5xx, así que un payload legi
383
439
  con un código distinto de cero siempre se informa como `Tronzap::ApiError`, nunca
384
440
  como `Tronzap::HttpError`.
385
441
 
442
+ `ApiError#result` es el `result` que la API envió con el error, como JSON
443
+ analizado, o `nil`. El SDK lee los datos de `BULK_PRICE_CHANGED` y
444
+ `BULK_NO_VALID_ITEMS` en `Tronzap::BulkPriceChangedError#calculation` y
445
+ `Tronzap::BulkNoValidItemsError#rejected`; ambos son `ApiError`. Un límite de
446
+ solicitudes informado por la API es un `ApiError` con `RATE_LIMITED`;
447
+ `Tronzap::RateLimitError` es solo un HTTP 429 sin respuesta de la API, p. ej. de un
448
+ proxy. `ApiError` y `HttpError` incluyen `retry_after`, los segundos que esperar
449
+ según la cabecera `Retry-After` o el campo `retry_after`, o `nil` si el servidor no
450
+ indicó cuánto esperar:
451
+
452
+ ```ruby
453
+ rescue Tronzap::ApiError => e
454
+ raise unless e.code == Tronzap::ErrorCode::RATE_LIMITED
455
+
456
+ sleep(e.retry_after || 60)
457
+ end
458
+ ```
459
+
386
460
  ### Códigos de error de la API
387
461
 
388
462
  | Código | Constante | Descripción |
@@ -401,6 +475,14 @@ como `Tronzap::HttpError`.
401
475
  | 30 | `AML_CHECK_NOT_FOUND` | Verificación AML no encontrada |
402
476
  | 35 | `SERVICE_NOT_AVAILABLE` | Servicio no disponible |
403
477
  | 50 | `INVALID_BANDWIDTH_AMOUNT` | Cantidad de ancho de banda inválida |
478
+ | 90 | `BULK_NOT_FOUND` | Pedido masivo no encontrado |
479
+ | 91 | `BULK_EXPIRED` | El cálculo expiró, calcula de nuevo |
480
+ | 92 | `BULK_PRICE_CHANGED` | El precio cambió; el nuevo cálculo está en `BulkPriceChangedError#calculation` |
481
+ | 93 | `BULK_TOO_MANY_ITEMS` | Más de 10 000 filas |
482
+ | 94 | `BULK_NO_VALID_ITEMS` | No hay filas válidas; están en `BulkNoValidItemsError#rejected` |
483
+ | 95 | `BULK_RESOURCE_NOT_SUPPORTED` | Solo se puede pedir energía en masa |
484
+ | 96 | `PAYLOAD_TOO_LARGE` | Cuerpo de la solicitud demasiado grande (HTTP 413) |
485
+ | 429 | `RATE_LIMITED` | Demasiadas solicitudes; espera `retry_after` si se indica |
404
486
  | 500 | `INTERNAL_SERVER_ERROR` | Error interno del servidor: contacta con soporte |
405
487
 
406
488
  Las constantes están en `Tronzap::ErrorCode`. Un código que esta versión del SDK
data/README.md CHANGED
@@ -190,6 +190,12 @@ libraries need to be translated by the adapter, as above.
190
190
  | `check_subscription(id: nil, external_id: nil)` | `/v1/subscription/check` | Status of a subscription, by id or external id |
191
191
  | `stop_subscription(id: nil, external_id: nil)` | `/v1/subscription/stop` | Stop a subscription |
192
192
  | `get_subscription_history(page: 1, per_page: 10, status: nil)` | `/v1/subscriptions/history` | Paginated subscription history |
193
+ | `bulk_calculate(items:, duration: 1)` | `/v1/bulk/calculate` | Validate and price the rows of a bulk energy order |
194
+ | `bulk_create(id:, external_id: nil, force: false, max_price_increase: nil, webhook_url: nil)` | `/v1/bulk/create` | Start a bulk order from a calculation |
195
+ | `bulk_check(id: nil, external_id: nil)` | `/v1/bulk/check` | Status and progress of a bulk order |
196
+ | `get_bulk_history(page: 1, per_page: 10)` | `/v1/bulk/history` | Paginated bulk order history |
197
+ | `bulk_report(id: nil, external_id: nil, status: nil)` | `/v1/bulk/report` | Per-address report of a bulk order, as CSV |
198
+ | `verify_webhook_signature(body, signature)` | — | Check the `X-Signature` of a bulk order webhook |
193
199
 
194
200
  Methods with parameters take either keyword arguments or a request object from
195
201
  `Tronzap::Requests`, so a request can be built, validated and passed around before
@@ -315,6 +321,58 @@ instead, and leaves `params` `nil`. A subscription moves through the statuses in
315
321
  `Tronzap::Models::SUBSCRIPTION_STATUSES`. A subscription with a transactions limit
316
322
  cannot be stopped (`CANNOT_STOP_SUBSCRIPTION`).
317
323
 
324
+ ### Bulk orders
325
+
326
+ Buy energy for up to 10 000 addresses in one order. `bulk_calculate` validates and
327
+ prices the rows and returns a calculation valid for 10 minutes; nothing is
328
+ charged. Invalid rows do not fail the request: they come back in `rejected` with
329
+ their row number. `bulk_create` starts the order; each address is charged when it
330
+ is processed, and addresses that are not activated are skipped without a charge.
331
+
332
+ If the price changed since the calculation, `bulk_create` does not start the order
333
+ and raises `Tronzap::BulkPriceChangedError` (code `BULK_PRICE_CHANGED`). Its
334
+ `calculation` is the new calculation: confirm the new total, then start it by its
335
+ `id`.
336
+
337
+ ```ruby
338
+ calculation = client.bulk_calculate(items: [
339
+ { address: "TRecipientAddress1", amount: 65000 },
340
+ { address: "TRecipientAddress2", amount: 131000 }
341
+ ])
342
+ calculation.rejected.each { |row| puts "row #{row.row}: #{row.reason}" }
343
+
344
+ begin
345
+ order = client.bulk_create(id: calculation.id, external_id: "order-42",
346
+ webhook_url: "https://example.com/tronzap/bulk")
347
+ rescue Tronzap::BulkPriceChangedError => e
348
+ new_calculation = e.calculation # confirm the new total, then start it
349
+ order = client.bulk_create(id: new_calculation.id, external_id: "order-42")
350
+ end
351
+
352
+ order = client.bulk_check(external_id: "order-42") # poll until :completed, :partial or :failed
353
+ csv = client.bulk_report(id: order.id) # row,address,amount,status,reason,charged,transaction_id
354
+ history = client.get_bulk_history(page: 1, per_page: 10)
355
+ ```
356
+
357
+ The rows are `Tronzap::Requests::BulkItem`s or hashes with `address` and `amount`.
358
+ An order moves through the statuses in `Tronzap::Models::BULK_STATUSES`;
359
+ `:completed`, `:partial` and `:failed` are final. `status:` of `bulk_report` takes
360
+ one of `Tronzap::Models::BULK_ROW_STATUSES`.
361
+
362
+ With `webhook_url`, the API sends one `POST` to it when the order becomes final.
363
+ Check its `X-Signature` header against the raw body before trusting it, for
364
+ example in Sinatra:
365
+
366
+ ```ruby
367
+ post "/tronzap/bulk" do
368
+ body = request.body.read
369
+ halt 401 unless client.verify_webhook_signature(body, request.env["HTTP_X_SIGNATURE"])
370
+
371
+ order = JSON.parse(body) # {"id":"01kb2m5x9qj4v8n3c7d6e5f4g3","external_id":"order-42","status":"partial"}
372
+ 200
373
+ end
374
+ ```
375
+
318
376
  ## Error handling
319
377
 
320
378
  Every failure of an API call is a `Tronzap::Error`. Rescue a subclass to handle
@@ -324,7 +382,7 @@ one kind of failure:
324
382
  Tronzap::Error
325
383
  ├── Tronzap::ApiError — the API answered with a non-zero code
326
384
  ├── Tronzap::HttpError — non-2xx response without an API payload
327
- │ ├── Tronzap::RateLimitError — HTTP 429
385
+ │ ├── Tronzap::RateLimitError — HTTP 429 without an API payload
328
386
  │ ├── Tronzap::UnauthorizedError — HTTP 401 or 403
329
387
  │ └── Tronzap::ServerError — HTTP 5xx
330
388
  ├── Tronzap::InvalidResponseError — 2xx response the SDK could not read
@@ -337,8 +395,7 @@ Tronzap::Error
337
395
  `ApiError`, `HttpError` and `InvalidResponseError` carry the HTTP status
338
396
  (`status`) and the raw response body (`response_body`). `ApiError` also carries
339
397
  the API error code (`code`), the error key (`error_key`) and the request ID
340
- (`request_id`). `RateLimitError#retry_after` holds the `Retry-After` delay in
341
- seconds when the API sends one.
398
+ (`request_id`).
342
399
 
343
400
  Invalid arguments are not API failures: they raise `ArgumentError` before anything
344
401
  is sent.
@@ -359,8 +416,8 @@ rescue Tronzap::ApiError => e
359
416
  else
360
417
  warn "api error #{e.code}: #{e.message} (request #{e.request_id || "-"})"
361
418
  end
362
- rescue Tronzap::RateLimitError => e
363
- # Back off and retry, after e.retry_after seconds if the API sent it.
419
+ rescue Tronzap::RateLimitError
420
+ # HTTP 429 without an API payload, e.g. from a proxy: back off and retry.
364
421
  rescue Tronzap::UnauthorizedError
365
422
  # Bad token or signature.
366
423
  rescue Tronzap::TimeoutError, Tronzap::ServerError
@@ -378,6 +435,24 @@ with a 2xx status and others with a 4xx or 5xx status, so a readable payload wit
378
435
  a non-zero code is always reported as `Tronzap::ApiError`, never as
379
436
  `Tronzap::HttpError`.
380
437
 
438
+ `ApiError#result` is the `result` the API sent along with the error, as parsed
439
+ JSON, or `nil`. The SDK reads the data of `BULK_PRICE_CHANGED` and
440
+ `BULK_NO_VALID_ITEMS` into `Tronzap::BulkPriceChangedError#calculation` and
441
+ `Tronzap::BulkNoValidItemsError#rejected`; both are `ApiError`s. A rate limit
442
+ reported by the API is an `ApiError` with `RATE_LIMITED`;
443
+ `Tronzap::RateLimitError` is only an HTTP 429 without an API payload, such as one
444
+ from a proxy. `ApiError` and `HttpError` carry `retry_after`, the seconds to wait
445
+ from the `Retry-After` header or the `retry_after` field, `nil` when the server did
446
+ not say how long to wait:
447
+
448
+ ```ruby
449
+ rescue Tronzap::ApiError => e
450
+ raise unless e.code == Tronzap::ErrorCode::RATE_LIMITED
451
+
452
+ sleep(e.retry_after || 60)
453
+ end
454
+ ```
455
+
381
456
  ### API error codes
382
457
 
383
458
  | Code | Constant | Description |
@@ -396,6 +471,14 @@ a non-zero code is always reported as `Tronzap::ApiError`, never as
396
471
  | 30 | `AML_CHECK_NOT_FOUND` | AML check not found |
397
472
  | 35 | `SERVICE_NOT_AVAILABLE` | Service not available |
398
473
  | 50 | `INVALID_BANDWIDTH_AMOUNT` | Invalid bandwidth amount |
474
+ | 90 | `BULK_NOT_FOUND` | Bulk order not found |
475
+ | 91 | `BULK_EXPIRED` | The calculation expired, calculate again |
476
+ | 92 | `BULK_PRICE_CHANGED` | The price changed; the new calculation is in `BulkPriceChangedError#calculation` |
477
+ | 93 | `BULK_TOO_MANY_ITEMS` | More than 10 000 rows |
478
+ | 94 | `BULK_NO_VALID_ITEMS` | No valid rows; they are in `BulkNoValidItemsError#rejected` |
479
+ | 95 | `BULK_RESOURCE_NOT_SUPPORTED` | Only energy can be ordered in bulk |
480
+ | 96 | `PAYLOAD_TOO_LARGE` | Request body too large (HTTP 413) |
481
+ | 429 | `RATE_LIMITED` | Too many requests; wait `retry_after` if given |
399
482
  | 500 | `INTERNAL_SERVER_ERROR` | Internal server error – contact support |
400
483
 
401
484
  The constants live in `Tronzap::ErrorCode`. A code this SDK version does not know
data/README.pt-br.md CHANGED
@@ -189,6 +189,12 @@ outras bibliotecas HTTP precisam ser traduzidos pelo adaptador, como acima.
189
189
  | `check_subscription(id: nil, external_id: nil)` | `/v1/subscription/check` | Status de uma assinatura, por id ou id externo |
190
190
  | `stop_subscription(id: nil, external_id: nil)` | `/v1/subscription/stop` | Parar uma assinatura |
191
191
  | `get_subscription_history(page: 1, per_page: 10, status: nil)` | `/v1/subscriptions/history` | Histórico paginado de assinaturas |
192
+ | `bulk_calculate(items:, duration: 1)` | `/v1/bulk/calculate` | Validar e calcular as linhas de um pedido de energia em massa |
193
+ | `bulk_create(id:, external_id: nil, force: false, max_price_increase: nil, webhook_url: nil)` | `/v1/bulk/create` | Iniciar um pedido em massa a partir de um cálculo |
194
+ | `bulk_check(id: nil, external_id: nil)` | `/v1/bulk/check` | Status e progresso de um pedido em massa |
195
+ | `get_bulk_history(page: 1, per_page: 10)` | `/v1/bulk/history` | Histórico paginado de pedidos em massa |
196
+ | `bulk_report(id: nil, external_id: nil, status: nil)` | `/v1/bulk/report` | Relatório por endereço de um pedido em massa, em CSV |
197
+ | `verify_webhook_signature(body, signature)` | — | Verificar o `X-Signature` do webhook de um pedido em massa |
192
198
 
193
199
  Os métodos com parâmetros aceitam argumentos nomeados ou um objeto de requisição de
194
200
  `Tronzap::Requests`, então uma requisição pode ser montada, validada e repassada
@@ -317,6 +323,57 @@ retorna em vez disso os contadores de uso `transactions_used`, `energy_used` e
317
323
  `Tronzap::Models::SUBSCRIPTION_STATUSES`. Uma assinatura com limite de transações
318
324
  não pode ser parada (`CANNOT_STOP_SUBSCRIPTION`).
319
325
 
326
+ ### Pedidos em massa
327
+
328
+ Compre energia para até 10 000 endereços em um único pedido. `bulk_calculate`
329
+ valida e calcula as linhas e retorna um cálculo válido por 10 minutos; nada é
330
+ cobrado. Linhas inválidas não fazem a requisição falhar: elas voltam em `rejected`
331
+ com o número da linha. `bulk_create` inicia o pedido; cada endereço é cobrado
332
+ quando é processado, e endereços não ativados são pulados sem cobrança.
333
+
334
+ Se o preço mudou desde o cálculo, `bulk_create` não inicia o pedido e lança
335
+ `Tronzap::BulkPriceChangedError` (código `BULK_PRICE_CHANGED`). Seu `calculation` é
336
+ o novo cálculo: confirme o novo total e inicie-o pelo `id`.
337
+
338
+ ```ruby
339
+ calculation = client.bulk_calculate(items: [
340
+ { address: "TRecipientAddress1", amount: 65000 },
341
+ { address: "TRecipientAddress2", amount: 131000 }
342
+ ])
343
+ calculation.rejected.each { |row| puts "row #{row.row}: #{row.reason}" }
344
+
345
+ begin
346
+ order = client.bulk_create(id: calculation.id, external_id: "order-42",
347
+ webhook_url: "https://example.com/tronzap/bulk")
348
+ rescue Tronzap::BulkPriceChangedError => e
349
+ new_calculation = e.calculation # confirme o novo total e inicie-o
350
+ order = client.bulk_create(id: new_calculation.id, external_id: "order-42")
351
+ end
352
+
353
+ order = client.bulk_check(external_id: "order-42") # consulte até :completed, :partial ou :failed
354
+ csv = client.bulk_report(id: order.id) # row,address,amount,status,reason,charged,transaction_id
355
+ history = client.get_bulk_history(page: 1, per_page: 10)
356
+ ```
357
+
358
+ As linhas são `Tronzap::Requests::BulkItem` ou hashes com `address` e `amount`. Um
359
+ pedido passa pelos status de `Tronzap::Models::BULK_STATUSES`; `:completed`,
360
+ `:partial` e `:failed` são finais. `status:` de `bulk_report` aceita um de
361
+ `Tronzap::Models::BULK_ROW_STATUSES`.
362
+
363
+ Com `webhook_url`, a API envia um `POST` quando o pedido chega a um status final.
364
+ Verifique o cabeçalho `X-Signature` com o corpo bruto antes de confiar nele, por
365
+ exemplo no Sinatra:
366
+
367
+ ```ruby
368
+ post "/tronzap/bulk" do
369
+ body = request.body.read
370
+ halt 401 unless client.verify_webhook_signature(body, request.env["HTTP_X_SIGNATURE"])
371
+
372
+ order = JSON.parse(body) # {"id":"01kb2m5x9qj4v8n3c7d6e5f4g3","external_id":"order-42","status":"partial"}
373
+ 200
374
+ end
375
+ ```
376
+
320
377
  ## Tratamento de erros
321
378
 
322
379
  Toda falha de uma chamada à API é um `Tronzap::Error`. Capture uma subclasse para
@@ -326,7 +383,7 @@ tratar um tipo específico de falha:
326
383
  Tronzap::Error
327
384
  ├── Tronzap::ApiError — a API respondeu com um código diferente de zero
328
385
  ├── Tronzap::HttpError — resposta não 2xx sem payload da API
329
- │ ├── Tronzap::RateLimitError — HTTP 429
386
+ │ ├── Tronzap::RateLimitError — HTTP 429 sem resposta da API
330
387
  │ ├── Tronzap::UnauthorizedError — HTTP 401 ou 403
331
388
  │ └── Tronzap::ServerError — HTTP 5xx
332
389
  ├── Tronzap::InvalidResponseError — resposta 2xx que o SDK não conseguiu ler
@@ -339,8 +396,7 @@ Tronzap::Error
339
396
  `ApiError`, `HttpError` e `InvalidResponseError` trazem o status HTTP (`status`) e
340
397
  o corpo bruto da resposta (`response_body`). `ApiError` também traz o código de
341
398
  erro da API (`code`), a chave do erro (`error_key`) e o ID da requisição
342
- (`request_id`). `RateLimitError#retry_after` contém o intervalo de `Retry-After`
343
- em segundos quando a API o envia.
399
+ (`request_id`).
344
400
 
345
401
  Argumentos inválidos não são falhas da API: eles lançam `ArgumentError` antes de
346
402
  qualquer envio.
@@ -361,8 +417,8 @@ rescue Tronzap::ApiError => e
361
417
  else
362
418
  warn "api error #{e.code}: #{e.message} (request #{e.request_id || "-"})"
363
419
  end
364
- rescue Tronzap::RateLimitError => e
365
- # Aguarde e tente novamente, após e.retry_after segundos se a API o enviou.
420
+ rescue Tronzap::RateLimitError
421
+ # HTTP 429 sem resposta da API, p. ex. de um proxy: aguarde e tente novamente.
366
422
  rescue Tronzap::UnauthorizedError
367
423
  # Token ou assinatura incorretos.
368
424
  rescue Tronzap::TimeoutError, Tronzap::ServerError
@@ -380,6 +436,24 @@ com status 2xx e outras com 4xx ou 5xx, então um payload legível com código
380
436
  diferente de zero é sempre informado como `Tronzap::ApiError`, nunca como
381
437
  `Tronzap::HttpError`.
382
438
 
439
+ `ApiError#result` é o `result` que a API enviou com o erro, como JSON analisado,
440
+ ou `nil`. O SDK lê os dados de `BULK_PRICE_CHANGED` e `BULK_NO_VALID_ITEMS` em
441
+ `Tronzap::BulkPriceChangedError#calculation` e
442
+ `Tronzap::BulkNoValidItemsError#rejected`; os dois são `ApiError`. Um limite de
443
+ requisições informado pela API é um `ApiError` com `RATE_LIMITED`;
444
+ `Tronzap::RateLimitError` é apenas um HTTP 429 sem resposta da API, p. ex. de um
445
+ proxy. `ApiError` e `HttpError` trazem `retry_after`, os segundos de espera do
446
+ cabeçalho `Retry-After` ou do campo `retry_after`, ou `nil` quando o servidor não
447
+ informou quanto esperar:
448
+
449
+ ```ruby
450
+ rescue Tronzap::ApiError => e
451
+ raise unless e.code == Tronzap::ErrorCode::RATE_LIMITED
452
+
453
+ sleep(e.retry_after || 60)
454
+ end
455
+ ```
456
+
383
457
  ### Códigos de erro da API
384
458
 
385
459
  | Código | Constante | Descrição |
@@ -398,6 +472,14 @@ diferente de zero é sempre informado como `Tronzap::ApiError`, nunca como
398
472
  | 30 | `AML_CHECK_NOT_FOUND` | Verificação AML não encontrada |
399
473
  | 35 | `SERVICE_NOT_AVAILABLE` | Serviço indisponível |
400
474
  | 50 | `INVALID_BANDWIDTH_AMOUNT` | Quantidade de largura de banda inválida |
475
+ | 90 | `BULK_NOT_FOUND` | Pedido em massa não encontrado |
476
+ | 91 | `BULK_EXPIRED` | O cálculo expirou, calcule novamente |
477
+ | 92 | `BULK_PRICE_CHANGED` | O preço mudou; o novo cálculo está em `BulkPriceChangedError#calculation` |
478
+ | 93 | `BULK_TOO_MANY_ITEMS` | Mais de 10 000 linhas |
479
+ | 94 | `BULK_NO_VALID_ITEMS` | Nenhuma linha válida; elas estão em `BulkNoValidItemsError#rejected` |
480
+ | 95 | `BULK_RESOURCE_NOT_SUPPORTED` | Só energia pode ser pedida em massa |
481
+ | 96 | `PAYLOAD_TOO_LARGE` | Corpo da requisição grande demais (HTTP 413) |
482
+ | 429 | `RATE_LIMITED` | Requisições demais; aguarde `retry_after` se informado |
401
483
  | 500 | `INTERNAL_SERVER_ERROR` | Erro interno do servidor: contate o suporte |
402
484
 
403
485
  As constantes estão em `Tronzap::ErrorCode`. Um código que esta versão do SDK não
data/README.ru.md CHANGED
@@ -190,6 +190,12 @@ HTTP-библиотек адаптер должен преобразовать
190
190
  | `check_subscription(id: nil, external_id: nil)` | `/v1/subscription/check` | Статус подписки по id или внешнему id |
191
191
  | `stop_subscription(id: nil, external_id: nil)` | `/v1/subscription/stop` | Остановить подписку |
192
192
  | `get_subscription_history(page: 1, per_page: 10, status: nil)` | `/v1/subscriptions/history` | История подписок с пагинацией |
193
+ | `bulk_calculate(items:, duration: 1)` | `/v1/bulk/calculate` | Проверка и расчёт строк массового заказа энергии |
194
+ | `bulk_create(id:, external_id: nil, force: false, max_price_increase: nil, webhook_url: nil)` | `/v1/bulk/create` | Запуск массового заказа по расчёту |
195
+ | `bulk_check(id: nil, external_id: nil)` | `/v1/bulk/check` | Статус и прогресс массового заказа |
196
+ | `get_bulk_history(page: 1, per_page: 10)` | `/v1/bulk/history` | История массовых заказов с пагинацией |
197
+ | `bulk_report(id: nil, external_id: nil, status: nil)` | `/v1/bulk/report` | Отчёт массового заказа по адресам в CSV |
198
+ | `verify_webhook_signature(body, signature)` | — | Проверка `X-Signature` вебхука массового заказа |
193
199
 
194
200
  Методы с параметрами принимают либо именованные аргументы, либо объект запроса из
195
201
  `Tronzap::Requests`, поэтому запрос можно создать, проверить и передать дальше до
@@ -317,6 +323,57 @@ history = client.get_subscription_history(status: :active)
317
323
  `Tronzap::Models::SUBSCRIPTION_STATUSES`. Подписку с лимитом транзакций
318
324
  остановить нельзя (`CANNOT_STOP_SUBSCRIPTION`).
319
325
 
326
+ ### Массовые заказы
327
+
328
+ Покупка энергии на 10 000 адресов одним заказом. `bulk_calculate` проверяет и
329
+ рассчитывает строки и возвращает расчёт, действительный 10 минут; ничего не
330
+ списывается. Некорректные строки не валят запрос: они возвращаются в `rejected` с
331
+ номером строки. `bulk_create` запускает заказ; каждый адрес списывается в момент
332
+ обработки, неактивированные адреса пропускаются без списания.
333
+
334
+ Если цена изменилась после расчёта, `bulk_create` не запускает заказ и вызывает
335
+ `Tronzap::BulkPriceChangedError` (код `BULK_PRICE_CHANGED`). Его `calculation` —
336
+ новый расчёт: подтвердите новую сумму и запустите его по `id`.
337
+
338
+ ```ruby
339
+ calculation = client.bulk_calculate(items: [
340
+ { address: "TRecipientAddress1", amount: 65000 },
341
+ { address: "TRecipientAddress2", amount: 131000 }
342
+ ])
343
+ calculation.rejected.each { |row| puts "row #{row.row}: #{row.reason}" }
344
+
345
+ begin
346
+ order = client.bulk_create(id: calculation.id, external_id: "order-42",
347
+ webhook_url: "https://example.com/tronzap/bulk")
348
+ rescue Tronzap::BulkPriceChangedError => e
349
+ new_calculation = e.calculation # подтвердите новую сумму и запустите его
350
+ order = client.bulk_create(id: new_calculation.id, external_id: "order-42")
351
+ end
352
+
353
+ order = client.bulk_check(external_id: "order-42") # опрашивайте до :completed, :partial или :failed
354
+ csv = client.bulk_report(id: order.id) # row,address,amount,status,reason,charged,transaction_id
355
+ history = client.get_bulk_history(page: 1, per_page: 10)
356
+ ```
357
+
358
+ Строки — это `Tronzap::Requests::BulkItem` или хеши с `address` и `amount`. Заказ
359
+ проходит статусы из `Tronzap::Models::BULK_STATUSES`; `:completed`, `:partial` и
360
+ `:failed` — финальные. `status:` у `bulk_report` принимает одно из
361
+ `Tronzap::Models::BULK_ROW_STATUSES`.
362
+
363
+ С `webhook_url` API отправляет на него один `POST`, когда заказ становится
364
+ финальным. Перед тем как доверять ему, проверьте заголовок `X-Signature` по сырому
365
+ телу, например в Sinatra:
366
+
367
+ ```ruby
368
+ post "/tronzap/bulk" do
369
+ body = request.body.read
370
+ halt 401 unless client.verify_webhook_signature(body, request.env["HTTP_X_SIGNATURE"])
371
+
372
+ order = JSON.parse(body) # {"id":"01kb2m5x9qj4v8n3c7d6e5f4g3","external_id":"order-42","status":"partial"}
373
+ 200
374
+ end
375
+ ```
376
+
320
377
  ## Обработка ошибок
321
378
 
322
379
  Любой сбой вызова API — исключение `Tronzap::Error`. Перехватывайте подкласс, чтобы
@@ -326,7 +383,7 @@ history = client.get_subscription_history(status: :active)
326
383
  Tronzap::Error
327
384
  ├── Tronzap::ApiError — API ответил ненулевым code
328
385
  ├── Tronzap::HttpError — ответ не 2xx без payload API
329
- │ ├── Tronzap::RateLimitError — HTTP 429
386
+ │ ├── Tronzap::RateLimitError — HTTP 429 без ответа API
330
387
  │ ├── Tronzap::UnauthorizedError — HTTP 401 или 403
331
388
  │ └── Tronzap::ServerError — HTTP 5xx
332
389
  ├── Tronzap::InvalidResponseError — ответ 2xx, который SDK не смог прочитать
@@ -339,8 +396,6 @@ Tronzap::Error
339
396
  `ApiError`, `HttpError` и `InvalidResponseError` содержат HTTP-статус
340
397
  (`status`) и сырое тело ответа (`response_body`). `ApiError` также содержит код
341
398
  ошибки API (`code`), ключ ошибки (`error_key`) и ID запроса (`request_id`).
342
- `RateLimitError#retry_after` хранит задержку из `Retry-After` в секундах, если API
343
- её прислал.
344
399
 
345
400
  Невалидные аргументы не являются сбоями API: они вызывают `ArgumentError` ещё до
346
401
  отправки.
@@ -361,8 +416,8 @@ rescue Tronzap::ApiError => e
361
416
  else
362
417
  warn "api error #{e.code}: #{e.message} (request #{e.request_id || "-"})"
363
418
  end
364
- rescue Tronzap::RateLimitError => e
365
- # Подождите и повторите, через e.retry_after секунд, если API его прислал.
419
+ rescue Tronzap::RateLimitError
420
+ # HTTP 429 без ответа API, например от прокси: подождите и повторите.
366
421
  rescue Tronzap::UnauthorizedError
367
422
  # Неверный токен или подпись.
368
423
  rescue Tronzap::TimeoutError, Tronzap::ServerError
@@ -379,6 +434,23 @@ end
379
434
  часть — с 4xx или 5xx, поэтому читаемый payload с ненулевым кодом всегда
380
435
  сообщается как `Tronzap::ApiError`, а не как `Tronzap::HttpError`.
381
436
 
437
+ `ApiError#result` — поле `result`, которое API вернул вместе с ошибкой, в виде
438
+ разобранного JSON, или `nil`. Данные `BULK_PRICE_CHANGED` и `BULK_NO_VALID_ITEMS`
439
+ SDK читает в `Tronzap::BulkPriceChangedError#calculation` и
440
+ `Tronzap::BulkNoValidItemsError#rejected`; обе ошибки — это `ApiError`. Лимит
441
+ запросов, о котором сообщает API, — это `ApiError` с `RATE_LIMITED`;
442
+ `Tronzap::RateLimitError` — только HTTP 429 без ответа API, например от прокси.
443
+ `ApiError` и `HttpError` содержат `retry_after` — сколько секунд ждать, из
444
+ заголовка `Retry-After` или поля `retry_after`, или `nil`, если сервер не сообщил:
445
+
446
+ ```ruby
447
+ rescue Tronzap::ApiError => e
448
+ raise unless e.code == Tronzap::ErrorCode::RATE_LIMITED
449
+
450
+ sleep(e.retry_after || 60)
451
+ end
452
+ ```
453
+
382
454
  ### Коды ошибок API
383
455
 
384
456
  | Код | Константа | Описание |
@@ -397,6 +469,14 @@ end
397
469
  | 30 | `AML_CHECK_NOT_FOUND` | AML-проверка не найдена |
398
470
  | 35 | `SERVICE_NOT_AVAILABLE` | Сервис недоступен |
399
471
  | 50 | `INVALID_BANDWIDTH_AMOUNT` | Неверное количество bandwidth |
472
+ | 90 | `BULK_NOT_FOUND` | Массовый заказ не найден |
473
+ | 91 | `BULK_EXPIRED` | Расчёт истёк, рассчитайте заново |
474
+ | 92 | `BULK_PRICE_CHANGED` | Цена изменилась; новый расчёт в `BulkPriceChangedError#calculation` |
475
+ | 93 | `BULK_TOO_MANY_ITEMS` | Больше 10 000 строк |
476
+ | 94 | `BULK_NO_VALID_ITEMS` | Нет корректных строк; они в `BulkNoValidItemsError#rejected` |
477
+ | 95 | `BULK_RESOURCE_NOT_SUPPORTED` | Массово можно заказать только энергию |
478
+ | 96 | `PAYLOAD_TOO_LARGE` | Слишком большое тело запроса (HTTP 413) |
479
+ | 429 | `RATE_LIMITED` | Слишком много запросов; подождите `retry_after`, если указано |
400
480
  | 500 | `INTERNAL_SERVER_ERROR` | Внутренняя ошибка сервера: обратитесь в поддержку |
401
481
 
402
482
  Константы находятся в `Tronzap::ErrorCode`. Код, который эта версия SDK не знает,