Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<ruta>` 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
Expand Down
8 changes: 5 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -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=<version> the xhandler-rust v<version> release
# make sync a checkout of xhandler-rust (RUST_REPO), for development
Expand All @@ -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
Expand All @@ -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))

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
142 changes: 40 additions & 102 deletions src/xhandler/xsender/models.py
Original file line number Diff line number Diff line change
@@ -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."""

Expand Down Expand Up @@ -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
104 changes: 104 additions & 0 deletions src/xhandler/xsender/models_gen.py
Original file line number Diff line number Diff line change
@@ -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
Loading