From 3bc76ff4a840bce32cabd45042596b69999d71c8 Mon Sep 17 00:00:00 2001 From: Carlos Feria <2582866+carlosthe19916@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:42:23 -0500 Subject: [PATCH] feat(xsender): the answers are generated from the core's schema `make sync` now also copies src/xhandler/xsender/models_gen.py: the SUNAT answers (SendFileAnswer, VerifyResult, ConsultResult, CDR, Fault, NoCDR, ConsultStatus, Status) generated from the schema of the core, so a field added to them in xhandler-rust arrives with the next core sync (xhandler-rust docs/adrs/BINDINGS.md). They ignore fields a newer core adds. The hand-written copies are gone; SendResult extends SendFileAnswer, and xhandler.xsender exports the same names, with the same fields, as before. Co-Authored-By: Claude Opus 5.5 --- CONTRIBUTING.md | 9 +- Makefile | 8 +- pyproject.toml | 2 +- src/xhandler/xsender/models.py | 142 ++++++++--------------------- src/xhandler/xsender/models_gen.py | 104 +++++++++++++++++++++ 5 files changed, 155 insertions(+), 110 deletions(-) create mode 100644 src/xhandler/xsender/models_gen.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eaed31f..d6ef262 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,10 +27,11 @@ XHANDLER_E2E=true uv run pytest tests/test_e2e.py # crea, firma y envía una fa make sync CORE=6.0.0-alpha.1 # el núcleo de una versión de xhandler-rust ``` - `make sync` copia el núcleo, los modelos (`src/xhandler/xbuilder/models.py`) y el corpus de - conformidad (`testdata/conformance/`). No los edites a mano. La versión del paquete es la del - núcleo, y una versión solo se publica con el núcleo de la versión igual de xhandler-rust: - `make verify-core` lo comprueba. + `make sync` copia el núcleo, los modelos (`src/xhandler/xbuilder/models.py`), las respuestas de + SUNAT (`src/xhandler/xsender/models_gen.py`) y el corpus de conformidad + (`testdata/conformance/`). No los edites a mano. La versión del paquete es la del núcleo, y una + versión solo se publica con el núcleo de la versión igual de xhandler-rust: `make verify-core` + lo comprueba. Estos comandos descargan el `core.sh` de xhandler-rust (`xhandler-wasm/core.sh`) del tag del núcleo; `CORE_SH=` usa una copia local, p. ej. al cambiarlo allá. - En Python está lo que necesita IO: el cliente HTTP (httpx), los reintentos y el caché de tokens diff --git a/Makefile b/Makefile index 716ef00..9720fdd 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ -# The core (src/xhandler/_core/xhandler.wasm, src/xhandler/xbuilder/models.py and -# testdata/conformance) comes from xhandler-rust: +# The core (src/xhandler/_core/xhandler.wasm, the generated src/xhandler/xbuilder/models.py +# and src/xhandler/xsender/models_gen.py, and testdata/conformance) comes from xhandler-rust: # # make sync CORE= the xhandler-rust v release # make sync a checkout of xhandler-rust (RUST_REPO), for development @@ -13,7 +13,8 @@ RUST_REPO ?= ../xhandler-rust CORE ?= DIST := $(if $(CORE),.dist,$(RUST_REPO)/dist) -SYNCED := src/xhandler/_core/xhandler.wasm src/xhandler/_core/VERSION src/xhandler/xbuilder/models.py testdata/conformance +SYNCED := src/xhandler/_core/xhandler.wasm src/xhandler/_core/VERSION src/xhandler/xbuilder/models.py \ + src/xhandler/xsender/models_gen.py testdata/conformance # core.sh syncs and verifies a released core. It lives in xhandler-rust, next to the release # format it reads, and is downloaded from the tag of the core at hand (from main for a core @@ -31,6 +32,7 @@ core_sh = $(if $(CORE_SH),bash $(CORE_SH) $(2),script=$$(mktemp) && trap 'rm -f sync: dist cp $(DIST)/xhandler.wasm $(DIST)/VERSION src/xhandler/_core/ cp $(DIST)/models/python/models.py src/xhandler/xbuilder/models.py + cp $(DIST)/models/python/xsender/models_gen.py src/xhandler/xsender/models_gen.py rm -rf testdata/conformance && cp -r $(DIST)/conformance testdata/conformance $(if $(CORE),rm -rf $(DIST)) diff --git a/pyproject.toml b/pyproject.toml index ee4299e..7a8ac24 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -36,7 +36,7 @@ pythonpath = ["tests"] [tool.ruff] line-length = 100 -extend-exclude = ["src/xhandler/xbuilder/models.py"] +extend-exclude = ["src/xhandler/xbuilder/models.py", "src/xhandler/xsender/models_gen.py"] [tool.ruff.lint] select = ["E", "F", "I", "UP", "B", "SIM"] diff --git a/src/xhandler/xsender/models.py b/src/xhandler/xsender/models.py index c40222b..1694519 100644 --- a/src/xhandler/xsender/models.py +++ b/src/xhandler/xsender/models.py @@ -1,37 +1,51 @@ -"""Inputs and answers of the SUNAT services.""" +"""Inputs of the SUNAT services, and the answers: generated from the core's +schema in models_gen.py, re-exported here.""" from __future__ import annotations -import base64 from collections.abc import Iterator -from enum import Enum -from typing import Annotated, Any, Literal - -from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, PlainSerializer - - -def _from_base64(value: object) -> object: - return base64.b64decode(value) if isinstance(value, str) else value - - -Bytes = Annotated[ - bytes, - BeforeValidator(_from_base64), - PlainSerializer(lambda b: base64.b64encode(b).decode(), return_type=str, when_used="json"), +from typing import Any, Literal + +from pydantic import BaseModel, ConfigDict, Field + +# Bytes (raw bytes, base64 in JSON) also types the zip of File +from xhandler.xsender.models_gen import ( + CDR, + Bytes, + ConsultResult, + ConsultStatus, + Fault, + NoCDR, + SendFileAnswer, + Status, + VerifyResult, +) + +__all__ = [ + "BILL_CONSULT_SERVICE_URL", + "BILL_VALID_SERVICE_URL", + "CDR", + "ConsultDocument", + "ConsultResult", + "ConsultStatus", + "Credentials", + "Fault", + "File", + "NoCDR", + "SendFileAnswer", + "SendResult", + "Status", + "Target", + "URLs", + "ValidateCDP", + "VerifyResult", ] -"""Raw bytes in Python, base64 in the JSON of the core.""" class _Model(BaseModel): model_config = ConfigDict(extra="forbid", frozen=True) -class _Answer(BaseModel): - """An answer of the core: ignores the fields a newer core adds.""" - - model_config = ConfigDict(extra="ignore", frozen=True) - - class URLs(_Model): """The SUNAT services where a company sends its documents.""" @@ -121,86 +135,10 @@ class ValidateCDP(ConsultDocument): numero_autorizacion: str | None = None -class Status(str, Enum): - """The SUNAT verdict of a document; prints as SUNAT says it, e.g. ACEPTADO.""" - - ACCEPTED = "ACEPTADO" - REJECTED = "RECHAZADO" - EXCEPTION = "EXCEPCION" - IN_PROGRESS = "EN_PROCESO" - UNKNOWN = "UNKNOWN" - - def __str__(self) -> str: - return self.value - - -class CDR(_Answer): - """The receipt SUNAT gives back (Constancia de Recepcion).""" - - zip: Bytes - response_code: str - description: str - notes: list[str] - document_description: str | None = None - """For an accepted guía de remisión, the URL its printed copy's QR code must - encode; None for other documents (and with a core older than 6.0.0-alpha.2).""" - status: Status - status_code: str | None = None - """The ticket status, only when verifying a ticket.""" - - -class Fault(_Answer): - """An error answered by SUNAT.""" +class SendResult(SendFileAnswer): + """The answer to a sent file (a CDR, a ticket to verify later or a fault) + and where it went.""" - code: str - """SUNAT's code as given: the SOAP faultcode (e.g. "soap-env:Client.0111") or - the error code of a REST answer (e.g. "1033").""" - sunat_code: int | None = None - """The number in ``code`` (111), when it has one.""" - http_status: int | None = None - """The status of the answer, e.g. 500 for SOAP faults or 422 for REST errors.""" - message: str - status: Status - - -class NoCDR(_Answer): - """A ticket status without CDR, e.g. "98" (in progress).""" - - status_code: str - status: Status - - -class SendResult(_Answer): - """The answer to a sent file: a CDR, a ticket to verify later (summaries, - voided documents, packs, guias) or a fault.""" - - cdr: CDR | None = None - ticket: str | None = None - fault: Fault | None = None send_target: Target verify_ticket_target: Target | None = None """Where the ticket is verified.""" - - -class VerifyResult(_Answer): - """The answer to a ticket: a CDR, no CDR yet (e.g. in progress) or a fault.""" - - cdr: CDR | None = None - no_cdr: NoCDR | None = None - fault: Fault | None = None - - -class ConsultStatus(_Answer): - """e.g. "0001" (accepted) for get_status, or "0" for validate_cdp.""" - - status_code: str - status_message: str | None = None - cdr_zip: Bytes | None = None - """The CDR of get_status_cdr.""" - - -class ConsultResult(_Answer): - """The answer of the consult and validation services.""" - - status: ConsultStatus | None = None - fault: Fault | None = None diff --git a/src/xhandler/xsender/models_gen.py b/src/xhandler/xsender/models_gen.py new file mode 100644 index 0000000..2b9030f --- /dev/null +++ b/src/xhandler/xsender/models_gen.py @@ -0,0 +1,104 @@ +"""Code generated by xhandler-wasm/codegen.py from xhandler.schema.json. DO NOT EDIT.""" + +from __future__ import annotations + +import base64 +from enum import Enum +from typing import Annotated + +from pydantic import BaseModel, BeforeValidator, ConfigDict, PlainSerializer + +__all__ = ['CDR', 'ConsultResult', 'ConsultStatus', 'Fault', 'NoCDR', 'SendFileAnswer', 'Status', 'VerifyResult'] + + +def _from_base64(value: object) -> object: + return base64.b64decode(value) if isinstance(value, str) else value + + +Bytes = Annotated[ + bytes, + BeforeValidator(_from_base64), + PlainSerializer(lambda b: base64.b64encode(b).decode(), return_type=str, when_used="json"), +] +"""Raw bytes in Python, base64 in the JSON of the core.""" + + +class _Model(BaseModel): + model_config = ConfigDict(extra="ignore", frozen=True) + + +class Status(str, Enum): + """The SUNAT verdict of a document, from its response code""" + ACCEPTED = 'ACEPTADO' + REJECTED = 'RECHAZADO' + EXCEPTION = 'EXCEPCION' + IN_PROGRESS = 'EN_PROCESO' + UNKNOWN = 'UNKNOWN' + + def __str__(self) -> str: + return self.value + + +class CDR(_Model): + """The receipt SUNAT gives back (Constancia de Recepción)""" + zip: Bytes + """The CDR zip""" + response_code: str + description: str + notes: list[str] + document_description: str | None = None + """For an accepted guía de remisión, the URL its printed copy's QR code + must encode; null for other documents""" + status: Status + status_code: str | None = None + """The ticket status, only when verifying a ticket""" + + +class ConsultStatus(_Model): + """A status of the consult services: e.g. "0001" (accepted) for getStatus, or + "0" for validaCDPcriterios""" + status_code: str + status_message: str | None = None + cdr_zip: Bytes | None = None + """The CDR zip of getStatusCdr""" + + +class Fault(_Model): + """An error answered by SUNAT""" + code: str + """SUNAT's code as given: the SOAP faultcode (e.g. "soap-env:Client.0111") + or the error code of a REST answer (e.g. "1033")""" + sunat_code: int | None = None + """The number in `code` (111), when it has one""" + http_status: int | None = None + """The status of the answer, e.g. 500 for SOAP faults or 422 for REST + errors""" + message: str + status: Status + + +class ConsultResult(_Model): + """The answer of the consult and validation services""" + status: ConsultStatus | None = None + fault: Fault | None = None + + +class NoCDR(_Model): + """A ticket status without CDR, e.g. "98" (in progress)""" + status_code: str + status: Status + + +class SendFileAnswer(_Model): + """The answer to a sent file: a CDR, a ticket to verify later (summaries, + voided documents, packs, guías) or a fault""" + cdr: CDR | None = None + ticket: str | None = None + fault: Fault | None = None + + +class VerifyResult(_Model): + """The answer to a ticket: a CDR, no CDR yet (e.g. in progress) or a fault""" + cdr: CDR | None = None + no_cdr: NoCDR | None = None + fault: Fault | None = None