Skip to main content

rfbcalc

CI License: MIT Python 3.11+

rfbcalc — cliente Python tipado, não-oficial, da calculadora oficial da Receita Federal para CBS/IBS/IS (piloto-cbs)

Typed Python client for the official Receita Federal do Brasil calculator for CBS, IBS and Imposto Seletivo (Reforma Tributária do Consumo, LC 214/2025).

⚠️ AVISO / DISCLAIMER

PT-BR — Este projeto não é da Receita Federal e não é oficial. Ele apenas transporta dados para a calculadora oficial e devolve a resposta dela. Nenhuma alíquota, base de cálculo ou regra da LC 214/2025 é implementada aqui. O motor oficial é a única fonte da verdade. O motor está em VERSÃO BETA (ambiente piloto) e seus resultados não substituem orientação fiscal ou jurídica.

EN — This project is not the Receita Federal and is not official. It only transports data to the official calculator and returns its answer. No rate, calculation base or LC 214/2025 rule is implemented here. The official engine is the single source of truth. That engine is in BETA (pilot environment) and its results are not tax or legal advice.


PT-BR

O que é

rfbcalc é um cliente Python não-oficial e tipado (Pydantic v2) para a Calculadora de Tributos sobre o Consumo da Receita Federal.

O que a biblioteca faz:

  • monta o payload JSON com os nomes de campo oficiais;
  • envia ao motor oficial (online ou offline);
  • devolve a resposta tipada, com valores monetários em Decimal (sem float).

O que a biblioteca não faz: calcular tributo. Todo número vem do motor oficial.

Instalação

pip install rfbcalc          # a partir do PyPI (quando publicado)
pip install -e '.[dev]'      # a partir do repositório

Requer Python 3.11+. O pacote é tipado (py.typed).

Uso

from rfbcalc import Calculator

with Calculator() as calc:
    # Base de cálculo de CBS/IBS - POST /calculadora/base-calculo/cbs-ibs-mercadorias
    base = calc.base_calculo_cbs_ibs(
        anoFatoGerador=2026,
        valorBem="1000.00",
        icms="180.00",
        pis="16.50",
        cofins="76.00",
        frete="50.00",
        descontoIncondicional="30.00",
    )
    print(base.baseCalculo)          # Decimal('747.50'), calculado pelo motor oficial

    # Base de cálculo do Imposto Seletivo - POST /calculadora/base-calculo/is-mercadorias
    calc.base_calculo_imposto_seletivo(anoFatoGerador=2027, valorBem="1000.00", icms="180.00")

    # Cálculo completo da operação - POST /calculadora/regime-geral
    resultado = calc.regime_geral({
        "id": "op-001",
        "versao": "1.0.0",
        "dhFatoGerador": "2026-01-15T10:00:00-03:00",
        "municipio": 3550308,                       # São Paulo/SP
        "itens": [{
            "numero": 1,
            "cst": "000",
            "cClassTrib": "000001",
            "baseCalculo": "1000.00",
        }],
    })
    print(resultado.vBC, resultado.vIBS, resultado.vCBS, resultado.vIS)

Os nomes dos campos são idênticos aos da API oficial (camelCase, em português). Isso é proposital: qualquer atributo pode ser conferido diretamente no OpenAPI oficial, sem uma camada de tradução que possa introduzir erro.

Valores monetários são sempre Decimal. A resposta é desserializada com parse_float=Decimal, então nenhum centavo se perde num float.

Erros

Erros do motor oficial (RFC 7807 problem+json) viram RfbCalcError:

from rfbcalc import Calculator, RfbCalcError

try:
    with Calculator() as calc:
        calc.base_calculo_cbs_ibs(anoFatoGerador=1800, valorBem="100.00")
except RfbCalcError as exc:
    print(exc.status_code)   # 400
    print(exc.problem)       # payload completo devolvido pela Receita

CLI

rfbcalc versao
rfbcalc base-calculo-cbs-ibs anoFatoGerador=2026 valorBem=1000.00 icms=180.00
rfbcalc base-calculo-is anoFatoGerador=2027 valorBem=1000.00 icms=180.00
rfbcalc regime-geral operacao.json          # use '-' para stdin
rfbcalc demo

Códigos de saída: 0 sucesso, 1 erro do motor oficial ou de rede, 2 entrada inválida.

Demonstração

make demo

Um comando: cria o virtualenv, instala o pacote, chama o motor oficial ao vivo e compara cada valor, até o centavo, com um resultado oficial gravado em src/rfbcalc/fixtures/official_responses.json.

Esse arquivo não foi escrito à mão: ele é gravado verbatim do motor oficial por scripts/record_fixtures.py (make record-fixtures) e guarda a versão do motor e da base de referência usadas. Se a Receita mudar um valor, o make demo falha — que é exatamente o comportamento desejado.

Motor offline

O motor online é o padrão. A Receita também publica uma calculadora offline oficial que expõe a mesma API em http://localhost:8080/api.

make demo-offline       # baixa, sobe o motor oficial offline, roda a demo e derruba no fim
make offline-start      # apenas sobe o motor
make offline-stop

Requer Docker. O pacote oficial (calculadora.zip) não contém um .jar solto: ele traz calculadora.tar.gz, uma imagem de contêiner com o api-regime-geral.jar dentro. Por isso o make offline-start segue exatamente o caminho oficial documentado pela Receita (linux/1-instalar.sh e linux/2-executar.sh do próprio pacote):

docker import ./calculadora.tar.gz calculadora-image
docker run -t -i --rm -p 8080:8080 -p 8081:8081 -p 80:80 \
  -w /calculadora --name calculadora-container calculadora-image bash start.sh

O make offline-start publica apenas 8080 e 8081; a porta 80 (portal web) exige privilégios que a demo não precisa. O download é de ~250 MB e vem do endereço publicado pela própria Receita.

Em Python, basta apontar o cliente para o motor local:

from rfbcalc import Calculator

with Calculator.offline() as calc:               # http://localhost:8080/api
    calc.base_calculo_cbs_ibs(anoFatoGerador=2026, valorBem="1000.00")

Os motores online e offline foram verificados lado a lado: para os casos da demo eles devolvem exatamente os mesmos valores.

Desenvolvimento

make check         # ruff + mypy + pytest
make test          # testes unitários (sem rede)
make test-live     # testes contra o motor oficial de verdade
make help

Os testes de CI não acessam a rede: as respostas oficiais são reproduzidas com respx a partir do fixture gravado. Assim o CI não depende de um serviço do governo estar no ar, mas os números continuam sendo os oficiais.

Release: atualize __version__ em src/rfbcalc/__init__.py e o CHANGELOG.md, crie a tag vX.Y.Z e faça push. O workflow release.yml constrói e publica no PyPI (trusted publishing, sem token no repositório).


English

What it is

rfbcalc is an unofficial, typed (Pydantic v2) Python client for the Receita Federal do Brasil consumption-tax calculator covering CBS, IBS and Imposto Seletivo under LC 214/2025.

The library builds the JSON payload using the official field names, sends it to the official engine (online or offline), and returns a typed response with monetary values as Decimal. It computes no tax of its own — every number comes from the official engine.

Install

pip install rfbcalc          # from PyPI (once published)
pip install -e '.[dev]'      # from a clone of this repository

Python 3.11+. Ships py.typed.

Quickstart

from rfbcalc import Calculator

with Calculator() as calc:
    base = calc.base_calculo_cbs_ibs(
        anoFatoGerador=2026, valorBem="1000.00",
        icms="180.00", pis="16.50", cofins="76.00",
    )
    print(base.baseCalculo)   # Decimal, straight from the official engine

Field names mirror the official API verbatim (camelCase, Portuguese) so every attribute can be cross-checked against the official OpenAPI document. There is no translation layer that could silently introduce an error.

Covered endpoints

Method Path Client
POST /calculadora/base-calculo/cbs-ibs-mercadorias base_calculo_cbs_ibs()
POST /calculadora/base-calculo/is-mercadorias base_calculo_imposto_seletivo()
POST /calculadora/regime-geral regime_geral()
GET /calculadora/dados-abertos/versao versao()

Base URL: https://piloto-cbs.tributos.gov.br/servico/calculadora-consumo/api (no API key required as of 2026-09).

Responses use extra="allow", so fields added by the engine — which is under active development — reach the caller instead of being dropped.

Demo

make demo

Sets up a virtualenv, installs the package, calls the live official engine and asserts every value matches a recorded official result to the centavo. The expected numbers are recorded verbatim from the engine by make record-fixtures, never written by hand.

Offline engine

The Receita also publishes an official offline calculator exposing the same API on http://localhost:8080/api.

make demo-offline    # downloads, starts the official offline engine, runs the demo, tears it down

Requires Docker. The official package contains no loose .jar — it ships calculadora.tar.gz, a container image with api-regime-geral.jar inside — so offline-start follows the Receita's own documented route (docker import + docker run … bash start.sh, per linux/1-instalar.sh and linux/2-executar.sh in the official package).

In Python, Calculator.offline() targets http://localhost:8080/api.

Both engines were checked side by side: for the demo cases they return identical values.

Development

make check       # ruff + mypy + pytest
make test-live   # exercise the real official engine

Citation

See CITATION.cff.

License

MIT — see LICENSE. The official calculator itself belongs to the Receita Federal do Brasil and is governed by its own terms.

Metadata

Release files for rfbcalc 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rfbcalc 0.1.0
File Size Uploaded Provenance Actions
rfbcalc-0.1.0.tar.gz 359.8 kB With provenance Details for rfbcalc-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rfbcalc 0.1.0
File Interpreter ABI Platform Actions
rfbcalc-0.1.0-py3-none-any.whl Python 3 none any Details for rfbcalc-0.1.0-py3-none-any.whl

Total release size: 378.0 kB

Release files / rfbcalc-0.1.0.tar.gz

Download URL rfbcalc-0.1.0.tar.gz
Size 359.8 kB
Tags Source
SHA-256 checksum
How to use checksums
de529d0e5a183f9497a3c1e0c4cd26493396ca3a6f28d346000fa02904f4f067
BLAKE2b-256 checksum
How to use checksums
1686923caed6317898517febb1a2adff3a9b98b8c56c44010aba2414d03c0d05
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.

Transparency log

Release files / rfbcalc-0.1.0-py3-none-any.whl

Download URL rfbcalc-0.1.0-py3-none-any.whl
Size 18.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
004eacbeebbeb7936dda3e53ccf260afda9ff32c7fe27fb8c18b2955fa03596e
BLAKE2b-256 checksum
How to use checksums
90a682d942869a06a4308210c162262ca68e79eb929809030a0850cf17c44eb8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.

Transparency log

Security for rfbcalc 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for rfbcalc-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page