aeat.application.modelo._export module

Modelo declaration export: write a verified-complete or filed calculation revision to a local AEAT-compatible file.

export_modelo_revision() accepts a CalculationRevision id, rebuilds and approves a ModeloDraft from the revision replay inputs, then writes a fichero-BOE-formatted artefact to the operator-supplied output path. A MODELO_EXPORTED event is appended to the BucketEventHistoryRepository.

Export consumes the registry-authored fichero-BOE layouts through the filing runtime schema provider; Python code owns orchestration and safety checks, while the registry remains the authority for record fields, casillas, header keys, and provenance. The service refuses non-exportable revision states, cross-bucket targets, missing profile facts, unclean cross-period prerequisites, unmatched IVA wallet decisions, missing ledger evidence, and unusable output paths before the operator-visible file is committed.

The service is local-only: it never contacts AEAT and never invokes require_live_read. Export is fundamentally an offline operation that produces a file the operator presents through sede.agenciatributaria.gob.es themselves.

The CLI verb aeat app modelo export is a thin delegate over this service.

See also

revision_filing_replay_inputs():

Reconstructs the filing inputs from the persisted revision.

build_draft():

Builds the transient registry-backed draft that is exported.

export_draft():

Serializes the approved draft through registry export layouts.

require_cross_period_clean_state():

Rechecks cross-period filing prerequisites before writing the export.

resolve_modelo_result_disposition():

Determines the fichero declaration type and refund disposition.

class ModeloIvaWalletDecisionProvenance(**data)[source]

Bases: BaseModel

Redacted audit join for the Modelo 303 IVA wallet authority decision.

This intentionally excludes taxpayer identifiers, wallet amounts, and local recurrence amounts. The fingerprint lets audits join back to encrypted secure-object storage without copying live fiscal values into export events or result payloads.

Parameters:
  • decision_ref (_Sha256Ref)

  • selected_authority (str)

  • divergence (str)

  • target_year (int)

  • target_period (Period)

  • authority_source_kinds (tuple[str, ...])

  • authority_source_refs (tuple[_Sha256Ref, ...])

decision_ref: _Sha256Ref
selected_authority: str
divergence: str
target_year: int
target_period: Period
authority_source_kinds: tuple[str, ...]
authority_source_refs: tuple[_Sha256Ref, ...]
exception ModeloExportCrossBucketRefusedError(message=None, *, context=None, suggestion=None, translated_message=None)[source]

Bases: ModeloError

Raised when the addressed revision’s parent work unit belongs to a bucket other than the active profile bucket.

Bucket events must scope to the active bucket; allowing the service to emit into a foreign bucket would let any caller pollute another operator’s history.

Parameters:
  • message (str | None)

  • context (Mapping[str, object] | None)

  • suggestion (str | None)

  • translated_message (str | None)

Return type:

None

code: ClassVar[ErrorCode]
exception ModeloExportNoActiveBucketError(message=None, *, context=None, suggestion=None, translated_message=None)[source]

Bases: ModeloError

Raised when no active profile bucket is configured.

Export needs an active bucket because the resulting MODELO_EXPORTED event is scoped to a bucket id and the work-unit lookup is bucket-bound.

Parameters:
  • message (str | None)

  • context (Mapping[str, object] | None)

  • suggestion (str | None)

  • translated_message (str | None)

Return type:

None

code: ClassVar[ErrorCode]
exception ModeloExportEvidenceMissingError(message=None, *, context=None, suggestion=None, translated_message=None)[source]

Bases: ModeloExportError

Raised when a ledger-derived revision lacks exportable evidence.

Parameters:
  • message (str | None)

  • context (Mapping[str, object] | None)

  • suggestion (str | None)

  • translated_message (str | None)

Return type:

None

code: ClassVar[ErrorCode]
exception ModeloExportUnsupportedError(message=None, *, context=None, suggestion=None, translated_message=None)[source]

Bases: ModeloExportError

Raised when a modelo revision has no renderable local fichero-BOE export layout.

Parameters:
  • message (str | None)

  • context (Mapping[str, object] | None)

  • suggestion (str | None)

  • translated_message (str | None)

Return type:

None

code: ClassVar[ErrorCode]
exception ModeloExportOutputPathError(message=None, *, context=None, suggestion=None, translated_message=None)[source]

Bases: ModeloExportError

Raised when the operator-supplied --output path cannot receive the artefact.

Validated up front, before any fichero-BOE bytes are written, so an unusable destination (empty path, an existing directory, a missing or unwritable parent directory) is refused with a typed, operator-facing message instead of surfacing a raw OSError traceback from the atomic-rename write — and crucially before any cleartext financial bytes touch disk.

Parameters:
  • message (str | None)

  • context (Mapping[str, object] | None)

  • suggestion (str | None)

  • translated_message (str | None)

Return type:

None

code: ClassVar[ErrorCode]
class ModeloExportCommand(**data)[source]

Bases: BaseModel

Strict input contract for export_modelo_revision().

Variables:
  • calculation_revision_id – SHA-256 hex id of the calculation revision to export. Must be in VERIFICADO_COMPLETO or FILED state.

  • output_path – Absolute or working-directory-relative path to write the fichero-BOE artefact. Parent directories are created if missing.

  • actor – Operator identifier captured into the MODELO_EXPORTED event payload and used as the draft approved_by field for the transient export draft.

  • refund_election – The operator’s per-filing Modelo 303 negative-result disposition election threaded into the shared disposition resolver so the exported fichero “Tipo de declaración” matches the election made at filing. Defaults to COMPENSAR; DEVOLVER requests the credit back and is honoured only for a lawful refund period (refused otherwise).

Parameters:
  • calculation_revision_id (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=64, max_length=64, pattern=^[0-9a-f]{64}$, ascii_only=None)])

  • output_path (Path)

  • actor (str)

  • refund_election (RefundElection)

calculation_revision_id: CalculationRevisionId
output_path: Path
actor: str
refund_election: RefundElection
class ModeloExportResult(**data)[source]

Bases: BaseModel

Receipt produced by export_modelo_revision().

Composes the lower-level DeclaracionExportResult (already a byte-level receipt of the written file) with the work-unit-level identity the operator addresses.

Variables:
  • calculation_revision_id – The exported revision id.

  • work_unit_id – The parent work unit’s id.

  • bucket_id – The bucket the work unit lives in (always equal to the active profile bucket at export time).

  • modelo – AEAT modelo identifier.

  • filing_year – AEAT filing year.

  • period – Filing period as a typed Period value.

  • output_path – Absolute path the file was written to.

  • byte_size – Size of the written file in bytes.

  • file_sha256 – Hex-encoded SHA-256 of the written bytes.

  • format – Wire format string (currently always "fichero-boe").

  • exported_at – UTC timestamp of the write.

  • actor – Operator identifier captured into the event.

  • bucket_event_id – Id of the MODELO_EXPORTED event appended to the catalogue.

  • casilla_provenance – Regulatory grounding for casillas covered by the exported fichero-BOE layout.

Parameters:
  • calculation_revision_id (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=64, max_length=64, pattern=^[0-9a-f]{64}$, ascii_only=None)])

  • work_unit_id (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=64, max_length=64, pattern=^[0-9a-f]{64}$, ascii_only=None)])

  • bucket_id (Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=128, pattern=None, ascii_only=None)])

  • modelo (str)

  • filing_year (int)

  • period (Period)

  • output_path (Path)

  • byte_size (int)

  • file_sha256 (str)

  • format (str)

  • exported_at (datetime)

  • actor (str)

  • bucket_event_id (str)

  • casilla_provenance (tuple[ModeloCasillaProvenance, ...])

  • iva_wallet_decision_provenance (ModeloIvaWalletDecisionProvenance | None)

  • local_evidence_status (str)

  • official_evidence_message (str)

  • official_evidence_next_action (str)

  • completeness_unverified (bool)

calculation_revision_id: CalculationRevisionId
work_unit_id: WorkUnitId
bucket_id: BucketId
modelo: str
filing_year: int
period: Period
output_path: Path
byte_size: int
file_sha256: str
format: str
exported_at: datetime
actor: str
bucket_event_id: str
casilla_provenance: tuple[filing_domain.ModeloCasillaProvenance, ...]
iva_wallet_decision_provenance: ModeloIvaWalletDecisionProvenance | None
local_evidence_status: str
official_evidence_message: str
official_evidence_next_action: str
completeness_unverified: bool
property completeness_advisory_message: str

Operator-facing coverage advisory text for a completeness-unverified export.

iva_wallet_decision_export_provenance(decision)

Project an IVA wallet decision into a redacted export/event join record.

Return type:

ModeloIvaWalletDecisionProvenance | None

Parameters:

decision (IvaCompensationReconciliationDecision | None)

compose_export_headers(*, work_unit, revision, workflow_profile, period, refund_election=RefundElection.COMPENSAR)

Compose the full fichero-BOE export header dict for a revision.

Supplies every header key the modelo export layouts may declare as required (declaration_type, surnames, name, fecha_inicio_periodo, fecha_fin_periodo) plus the optional keys export can source cleanly (tax_id, presenter_nif, program_version, devengo_start_date, and the complementaria triple when the revision is an amendment).

_header_field_value only raises when a key is both declared required by the layout and missing, so over-supplying optional keys is safe — the renderer ignores headers a layout never reads.

Return type:

dict[str, str]

Parameters:
export_modelo_revision(command, *, workflow_profile, work_unit_repository=None, calculation_repository=None, filing_repository=None, verification_repository=None, bucket_event_repository=None, iva_compensation_decision_repository=None, calculation_observation_repository=None, cross_period_expected_member_sets=(), clock=None)[source]

Export a verified-complete or filed calculation revision to disk.

workflow_profile is the TaxpayerProfile used to compose the filing draft headers and to replay profile-applicability relation inputs.

Local-only: never contacts AEAT. Re-builds the filing draft from revision_filing_replay_inputs() so the exported file reflects the same legal casilla and relation map that would be filed.

The revision must be VERIFICADO_COMPLETO, PRESENTADO, or PRESENTADO_SUPERSEDIDO and must belong to the active bucket. Before writing any operator-visible file, the service validates the output path, export-layout renderability, profile readiness, ledger evidence, IVA wallet decision provenance, and cross-period clean state. It then rebuilds and approves a transient ModeloDraft, composes the fichero headers, serializes through export_draft(), appends MODELO_EXPORTED to the bucket-event-history catalogue, and finally atomically renames the sibling .tmp file into place. Any write, event, or rename failure removes the temporary cleartext artefact before raising.

Returns:

The export receipt, including byte size, digest, event id, casilla provenance, and any redacted IVA wallet decision provenance.

Return type:

ModeloExportResult

Parameters:

See also

ModeloExportCommand:

Strict input envelope for the revision id, output path, actor, and refund election.

_compose_export_headers():

Builds required fichero-BOE header keys from the work unit, profile, revision, period, amendment marker, and refund election.

_validate_output_path():

Refuses unsafe destinations before fichero bytes are written.