cirbethon 1.0.0__tar.gz

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.
Files changed (64) hide show
  1. cirbethon-1.0.0/.gitignore +14 -0
  2. cirbethon-1.0.0/PKG-INFO +94 -0
  3. cirbethon-1.0.0/README.md +79 -0
  4. cirbethon-1.0.0/pyproject.toml +37 -0
  5. cirbethon-1.0.0/src/cirbe/__init__.py +113 -0
  6. cirbethon-1.0.0/src/cirbe/cirbe_file.py +72 -0
  7. cirbethon-1.0.0/src/cirbe/cirbe_service.py +129 -0
  8. cirbethon-1.0.0/src/cirbe/enums/__init__.py +47 -0
  9. cirbethon-1.0.0/src/cirbe/enums/base.py +50 -0
  10. cirbethon-1.0.0/src/cirbe/enums/currency.py +19 -0
  11. cirbethon-1.0.0/src/cirbe/enums/gender.py +6 -0
  12. cirbethon-1.0.0/src/cirbe/enums/guarantee_coverage.py +7 -0
  13. cirbethon-1.0.0/src/cirbe/enums/header_result_code.py +20 -0
  14. cirbethon-1.0.0/src/cirbe/enums/holder_error_code.py +8 -0
  15. cirbethon-1.0.0/src/cirbe/enums/identifier_type.py +19 -0
  16. cirbethon-1.0.0/src/cirbe/enums/incident_type.py +9 -0
  17. cirbethon-1.0.0/src/cirbe/enums/institutional_sector.py +64 -0
  18. cirbethon-1.0.0/src/cirbe/enums/instrument_type.py +13 -0
  19. cirbethon-1.0.0/src/cirbe/enums/intervention_nature.py +7 -0
  20. cirbethon-1.0.0/src/cirbe/enums/legal_form.py +5 -0
  21. cirbethon-1.0.0/src/cirbe/enums/notification_code.py +62 -0
  22. cirbethon-1.0.0/src/cirbe/enums/person_nature.py +6 -0
  23. cirbethon-1.0.0/src/cirbe/enums/personal_guarantee_type.py +8 -0
  24. cirbethon-1.0.0/src/cirbe/enums/product_type.py +16 -0
  25. cirbethon-1.0.0/src/cirbe/enums/real_guarantee_type.py +26 -0
  26. cirbethon-1.0.0/src/cirbe/enums/request_reason.py +5 -0
  27. cirbethon-1.0.0/src/cirbe/enums/residual_term.py +10 -0
  28. cirbethon-1.0.0/src/cirbe/enums/situation.py +11 -0
  29. cirbethon-1.0.0/src/cirbe/enums/solidarity_type.py +6 -0
  30. cirbethon-1.0.0/src/cirbe/enums/street_type.py +36 -0
  31. cirbethon-1.0.0/src/cirbe/exceptions.py +49 -0
  32. cirbethon-1.0.0/src/cirbe/factories/__init__.py +3 -0
  33. cirbethon-1.0.0/src/cirbe/factories/record_factory.py +188 -0
  34. cirbethon-1.0.0/src/cirbe/models/__init__.py +43 -0
  35. cirbethon-1.0.0/src/cirbe/models/request/__init__.py +15 -0
  36. cirbethon-1.0.0/src/cirbe/models/request/individual_with_code_request_record.py +37 -0
  37. cirbethon-1.0.0/src/cirbe/models/request/individual_without_code_request_record.py +145 -0
  38. cirbethon-1.0.0/src/cirbe/models/request/legal_entity_with_code_request_record.py +35 -0
  39. cirbethon-1.0.0/src/cirbe/models/request/legal_entity_without_code_request_record.py +142 -0
  40. cirbethon-1.0.0/src/cirbe/models/request/request_header_record.py +34 -0
  41. cirbethon-1.0.0/src/cirbe/models/request/text_record.py +34 -0
  42. cirbethon-1.0.0/src/cirbe/models/response/__init__.py +23 -0
  43. cirbethon-1.0.0/src/cirbe/models/response/aggregate_data_record.py +54 -0
  44. cirbethon-1.0.0/src/cirbe/models/response/aggregate_incident_record.py +41 -0
  45. cirbethon-1.0.0/src/cirbe/models/response/anacredit_holder_record.py +23 -0
  46. cirbethon-1.0.0/src/cirbe/models/response/anacredit_incident_record.py +41 -0
  47. cirbethon-1.0.0/src/cirbe/models/response/anacredit_risk_record.py +31 -0
  48. cirbethon-1.0.0/src/cirbe/models/response/individual_error_record.py +20 -0
  49. cirbethon-1.0.0/src/cirbe/models/response/individual_without_code_response_record.py +85 -0
  50. cirbethon-1.0.0/src/cirbe/models/response/legal_entity_error_record.py +20 -0
  51. cirbethon-1.0.0/src/cirbe/models/response/legal_entity_without_code_response_record.py +85 -0
  52. cirbethon-1.0.0/src/cirbe/models/response/response_header_record.py +23 -0
  53. cirbethon-1.0.0/src/cirbe/models/value_objects/__init__.py +5 -0
  54. cirbethon-1.0.0/src/cirbe/models/value_objects/address.py +49 -0
  55. cirbethon-1.0.0/src/cirbe/models/value_objects/notification_block.py +22 -0
  56. cirbethon-1.0.0/src/cirbe/models/value_objects/person_code.py +32 -0
  57. cirbethon-1.0.0/src/cirbe/support/__init__.py +7 -0
  58. cirbethon-1.0.0/src/cirbe/support/field.py +50 -0
  59. cirbethon-1.0.0/src/cirbe/support/field_format.py +8 -0
  60. cirbethon-1.0.0/src/cirbe/support/fixed_width_record.py +198 -0
  61. cirbethon-1.0.0/src/cirbe/support/special_values.py +54 -0
  62. cirbethon-1.0.0/src/cirbe/support/text_normalizer.py +33 -0
  63. cirbethon-1.0.0/tests/__init__.py +0 -0
  64. cirbethon-1.0.0/tests/test_smoke.py +106 -0
@@ -0,0 +1,14 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ .pytest_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ .eggs/
10
+ *.egg
11
+ .ruff_cache/
12
+ .mypy_cache/
13
+ .coverage
14
+ htmlcov/
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.5
2
+ Name: cirbethon
3
+ Version: 1.0.0
4
+ Summary: Intercambio de informes CIRBE (Central de Información de Riesgos del Banco de España) en archivos de texto de ancho fijo. Proceso GRI-IE202501-V1.1.
5
+ Author-email: Jose Felipe Licea Munoz <felipelicea1989@gmail.com>
6
+ License: MIT
7
+ Requires-Python: >=3.12
8
+ Requires-Dist: pydantic>=2.9
9
+ Provides-Extra: dev
10
+ Requires-Dist: black>=24.0; extra == 'dev'
11
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
12
+ Requires-Dist: pytest>=8.0; extra == 'dev'
13
+ Requires-Dist: ruff>=0.8; extra == 'dev'
14
+ Description-Content-Type: text/markdown
15
+
16
+ # ciberthon
17
+
18
+ Librería Python para intercambiar informes con la **CIRBE** (Central de Información de Riesgos del Banco de España), proceso GRI-IE202501-V1.1.
19
+
20
+ Genera ficheros de petición y parsea ficheros de respuesta en formato de texto de ancho fijo (ISO-8859-1, registros de 1000 bytes, CRLF).
21
+
22
+ ## Instalación
23
+
24
+ ```bash
25
+ pip install cirbethon
26
+ ```
27
+
28
+ ## Uso rápido
29
+
30
+ ### Generar una petición
31
+
32
+ ```python
33
+ from cirbe import CirbeService, RequestHeaderRecord, TextRecord, LegalEntityWithCodeRequestRecord
34
+
35
+ svc = CirbeService()
36
+
37
+ header = RequestHeaderRecord.create('0001', 'MI ENTIDAD SL', '20250101')
38
+ text = TextRecord.create('0001')
39
+ req = LegalEntityWithCodeRequestRecord.create('0001', 'ESB12345678', 'EMPRESA CLIENTE SL')
40
+
41
+ content = svc.generate_request_file(header, text, legal_with_code=[req])
42
+
43
+ with open('peticion.txt', 'w', encoding='latin-1', newline='') as f:
44
+ f.write(content)
45
+ ```
46
+
47
+ ### Parsear una respuesta
48
+
49
+ ```python
50
+ from cirbe import CirbeService
51
+
52
+ svc = CirbeService()
53
+
54
+ with open('respuesta.txt', 'rb') as f:
55
+ result = svc.parse_response_file(f.read())
56
+
57
+ print(result.response_header.is_accepted()) # True / False
58
+ print(result.aggregates) # lista de CI001
59
+ print(result.legal_entity_assignments) # lista de AI002 de respuesta
60
+ ```
61
+
62
+ ## Tipos de registro soportados
63
+
64
+ | Código | Clase | Descripción |
65
+ |--------|-------|-------------|
66
+ | AI000 | `RequestHeaderRecord` / `ResponseHeaderRecord` | Cabecera |
67
+ | AI001 | `TextRecord` | Texto declarativo |
68
+ | AI002 | `LegalEntityWithCodeRequestRecord` | Persona jurídica con código |
69
+ | AI003 | `IndividualWithCodeRequestRecord` | Persona física con código |
70
+ | AI004 | `LegalEntityWithoutCodeRequestRecord` / `LegalEntityWithoutCodeResponseRecord` | Persona jurídica sin código |
71
+ | AI005 | `IndividualWithoutCodeRequestRecord` / `IndividualWithoutCodeResponseRecord` | Persona física sin código |
72
+ | CI001 | `AggregateDataRecord` | Datos agregados |
73
+ | CI002 | `AggregateIncidentRecord` | Incidencias agregadas |
74
+ | EI001 | `AnacreditHolderRecord` | Titular AnaCredit |
75
+ | EI002 | `AnacreditRiskRecord` | Riesgo AnaCredit |
76
+ | EI003 | `AnacreditIncidentRecord` | Incidencia AnaCredit |
77
+
78
+ ## Características
79
+
80
+ - Serialización y parseo completo de todos los tipos de registro CIRBE.
81
+ - Codificación ISO-8859-1 con soporte correcto de Ñ (1 byte en Latin-1).
82
+ - Normalización de texto: elimina tildes, filtra a caracteres CIRBE válidos.
83
+ - Validación de campos requeridos y valores de enumerados.
84
+ - Value objects Pydantic v2: `Address`, `PersonCode`, `NotificationBlock`, `CirbeFile`.
85
+ - Enumerados tipados (`CirbeEnum`) con `resolve()` y descripción en español.
86
+
87
+ ## Requisitos
88
+
89
+ - Python ≥ 3.12
90
+ - pydantic ≥ 2.9
91
+
92
+ ## Licencia
93
+
94
+ MIT
@@ -0,0 +1,79 @@
1
+ # ciberthon
2
+
3
+ Librería Python para intercambiar informes con la **CIRBE** (Central de Información de Riesgos del Banco de España), proceso GRI-IE202501-V1.1.
4
+
5
+ Genera ficheros de petición y parsea ficheros de respuesta en formato de texto de ancho fijo (ISO-8859-1, registros de 1000 bytes, CRLF).
6
+
7
+ ## Instalación
8
+
9
+ ```bash
10
+ pip install cirbethon
11
+ ```
12
+
13
+ ## Uso rápido
14
+
15
+ ### Generar una petición
16
+
17
+ ```python
18
+ from cirbe import CirbeService, RequestHeaderRecord, TextRecord, LegalEntityWithCodeRequestRecord
19
+
20
+ svc = CirbeService()
21
+
22
+ header = RequestHeaderRecord.create('0001', 'MI ENTIDAD SL', '20250101')
23
+ text = TextRecord.create('0001')
24
+ req = LegalEntityWithCodeRequestRecord.create('0001', 'ESB12345678', 'EMPRESA CLIENTE SL')
25
+
26
+ content = svc.generate_request_file(header, text, legal_with_code=[req])
27
+
28
+ with open('peticion.txt', 'w', encoding='latin-1', newline='') as f:
29
+ f.write(content)
30
+ ```
31
+
32
+ ### Parsear una respuesta
33
+
34
+ ```python
35
+ from cirbe import CirbeService
36
+
37
+ svc = CirbeService()
38
+
39
+ with open('respuesta.txt', 'rb') as f:
40
+ result = svc.parse_response_file(f.read())
41
+
42
+ print(result.response_header.is_accepted()) # True / False
43
+ print(result.aggregates) # lista de CI001
44
+ print(result.legal_entity_assignments) # lista de AI002 de respuesta
45
+ ```
46
+
47
+ ## Tipos de registro soportados
48
+
49
+ | Código | Clase | Descripción |
50
+ |--------|-------|-------------|
51
+ | AI000 | `RequestHeaderRecord` / `ResponseHeaderRecord` | Cabecera |
52
+ | AI001 | `TextRecord` | Texto declarativo |
53
+ | AI002 | `LegalEntityWithCodeRequestRecord` | Persona jurídica con código |
54
+ | AI003 | `IndividualWithCodeRequestRecord` | Persona física con código |
55
+ | AI004 | `LegalEntityWithoutCodeRequestRecord` / `LegalEntityWithoutCodeResponseRecord` | Persona jurídica sin código |
56
+ | AI005 | `IndividualWithoutCodeRequestRecord` / `IndividualWithoutCodeResponseRecord` | Persona física sin código |
57
+ | CI001 | `AggregateDataRecord` | Datos agregados |
58
+ | CI002 | `AggregateIncidentRecord` | Incidencias agregadas |
59
+ | EI001 | `AnacreditHolderRecord` | Titular AnaCredit |
60
+ | EI002 | `AnacreditRiskRecord` | Riesgo AnaCredit |
61
+ | EI003 | `AnacreditIncidentRecord` | Incidencia AnaCredit |
62
+
63
+ ## Características
64
+
65
+ - Serialización y parseo completo de todos los tipos de registro CIRBE.
66
+ - Codificación ISO-8859-1 con soporte correcto de Ñ (1 byte en Latin-1).
67
+ - Normalización de texto: elimina tildes, filtra a caracteres CIRBE válidos.
68
+ - Validación de campos requeridos y valores de enumerados.
69
+ - Value objects Pydantic v2: `Address`, `PersonCode`, `NotificationBlock`, `CirbeFile`.
70
+ - Enumerados tipados (`CirbeEnum`) con `resolve()` y descripción en español.
71
+
72
+ ## Requisitos
73
+
74
+ - Python ≥ 3.12
75
+ - pydantic ≥ 2.9
76
+
77
+ ## Licencia
78
+
79
+ MIT
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "cirbethon"
7
+ version = "1.0.0"
8
+ description = "Intercambio de informes CIRBE (Central de Información de Riesgos del Banco de España) en archivos de texto de ancho fijo. Proceso GRI-IE202501-V1.1."
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Jose Felipe Licea Munoz", email = "felipelicea1989@gmail.com" }]
13
+ dependencies = ["pydantic>=2.9"]
14
+
15
+ [project.optional-dependencies]
16
+ dev = ["pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.8", "black>=24.0"]
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/cirbe"]
20
+
21
+ [tool.pytest.ini_options]
22
+ testpaths = ["tests"]
23
+
24
+ [tool.black]
25
+ line-length = 100
26
+ target-version = ["py312"]
27
+
28
+ [tool.ruff]
29
+ line-length = 100
30
+ target-version = "py312"
31
+
32
+ [tool.ruff.lint]
33
+ select = ["E", "F", "I", "UP", "B", "SIM"]
34
+ ignore = ["E501"]
35
+
36
+ [tool.ruff.lint.isort]
37
+ known-first-party = ["cirbe"]
@@ -0,0 +1,113 @@
1
+ from .cirbe_file import CirbeFile
2
+ from .cirbe_service import CirbeService
3
+ from .enums import (
4
+ CurrencyEnum,
5
+ GenderEnum,
6
+ GuaranteeCoverageEnum,
7
+ HeaderResultCodeEnum,
8
+ HolderErrorCodeEnum,
9
+ IdentifierTypeEnum,
10
+ IncidentTypeEnum,
11
+ InstitutionalSectorEnum,
12
+ InstrumentTypeEnum,
13
+ InterventionNatureEnum,
14
+ LegalFormEnum,
15
+ NotificationCodeEnum,
16
+ PersonalGuaranteeTypeEnum,
17
+ PersonNatureEnum,
18
+ ProductTypeEnum,
19
+ RealGuaranteeTypeEnum,
20
+ RequestReasonEnum,
21
+ ResidualTermEnum,
22
+ SituationEnum,
23
+ SolidarityTypeEnum,
24
+ StreetTypeEnum,
25
+ )
26
+ from .exceptions import (
27
+ CirbeException,
28
+ InvalidRecordException,
29
+ UnsupportedRecordTypeException,
30
+ ValidationException,
31
+ )
32
+ from .factories import RecordFactory
33
+ from .models import (
34
+ Address,
35
+ AggregateDataRecord,
36
+ AggregateIncidentRecord,
37
+ AnacreditHolderRecord,
38
+ AnacreditIncidentRecord,
39
+ AnacreditRiskRecord,
40
+ IndividualErrorRecord,
41
+ IndividualWithCodeRequestRecord,
42
+ IndividualWithoutCodeRequestRecord,
43
+ IndividualWithoutCodeResponseRecord,
44
+ LegalEntityErrorRecord,
45
+ LegalEntityWithCodeRequestRecord,
46
+ LegalEntityWithoutCodeRequestRecord,
47
+ LegalEntityWithoutCodeResponseRecord,
48
+ NotificationBlock,
49
+ PersonCode,
50
+ RequestHeaderRecord,
51
+ ResponseHeaderRecord,
52
+ TextRecord,
53
+ )
54
+ from .support import Field, FieldFormat, FixedWidthRecord, SpecialValues, TextNormalizer
55
+
56
+ __all__ = [
57
+ 'CirbeFile',
58
+ 'CirbeService',
59
+ 'RecordFactory',
60
+ # enums
61
+ 'CurrencyEnum',
62
+ 'GenderEnum',
63
+ 'GuaranteeCoverageEnum',
64
+ 'HeaderResultCodeEnum',
65
+ 'HolderErrorCodeEnum',
66
+ 'IdentifierTypeEnum',
67
+ 'IncidentTypeEnum',
68
+ 'InstitutionalSectorEnum',
69
+ 'InstrumentTypeEnum',
70
+ 'InterventionNatureEnum',
71
+ 'LegalFormEnum',
72
+ 'NotificationCodeEnum',
73
+ 'PersonalGuaranteeTypeEnum',
74
+ 'PersonNatureEnum',
75
+ 'ProductTypeEnum',
76
+ 'RealGuaranteeTypeEnum',
77
+ 'RequestReasonEnum',
78
+ 'ResidualTermEnum',
79
+ 'SituationEnum',
80
+ 'SolidarityTypeEnum',
81
+ 'StreetTypeEnum',
82
+ # exceptions
83
+ 'CirbeException',
84
+ 'InvalidRecordException',
85
+ 'UnsupportedRecordTypeException',
86
+ 'ValidationException',
87
+ # models
88
+ 'Address',
89
+ 'AggregateDataRecord',
90
+ 'AggregateIncidentRecord',
91
+ 'AnacreditHolderRecord',
92
+ 'AnacreditIncidentRecord',
93
+ 'AnacreditRiskRecord',
94
+ 'IndividualErrorRecord',
95
+ 'IndividualWithCodeRequestRecord',
96
+ 'IndividualWithoutCodeRequestRecord',
97
+ 'IndividualWithoutCodeResponseRecord',
98
+ 'LegalEntityErrorRecord',
99
+ 'LegalEntityWithCodeRequestRecord',
100
+ 'LegalEntityWithoutCodeRequestRecord',
101
+ 'LegalEntityWithoutCodeResponseRecord',
102
+ 'NotificationBlock',
103
+ 'PersonCode',
104
+ 'RequestHeaderRecord',
105
+ 'ResponseHeaderRecord',
106
+ 'TextRecord',
107
+ # support
108
+ 'Field',
109
+ 'FieldFormat',
110
+ 'FixedWidthRecord',
111
+ 'SpecialValues',
112
+ 'TextNormalizer',
113
+ ]
@@ -0,0 +1,72 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from pydantic import BaseModel, ConfigDict
6
+
7
+ if TYPE_CHECKING:
8
+ from cirbe.models.response.aggregate_data_record import AggregateDataRecord
9
+ from cirbe.models.response.aggregate_incident_record import AggregateIncidentRecord
10
+ from cirbe.models.response.anacredit_holder_record import AnacreditHolderRecord
11
+ from cirbe.models.response.anacredit_incident_record import AnacreditIncidentRecord
12
+ from cirbe.models.response.anacredit_risk_record import AnacreditRiskRecord
13
+ from cirbe.models.response.individual_error_record import IndividualErrorRecord
14
+ from cirbe.models.response.individual_without_code_response_record import (
15
+ IndividualWithoutCodeResponseRecord,
16
+ )
17
+ from cirbe.models.response.legal_entity_error_record import LegalEntityErrorRecord
18
+ from cirbe.models.response.legal_entity_without_code_response_record import (
19
+ LegalEntityWithoutCodeResponseRecord,
20
+ )
21
+ from cirbe.models.response.response_header_record import ResponseHeaderRecord
22
+
23
+
24
+ class CirbeFile(BaseModel):
25
+ model_config = ConfigDict(arbitrary_types_allowed=True)
26
+
27
+ header: Any = None # ResponseHeaderRecord
28
+ legal_entity_errors: list[Any] = []
29
+ individual_errors: list[Any] = []
30
+ legal_entity_assignments: list[Any] = []
31
+ individual_assignments: list[Any] = []
32
+ aggregates: list[Any] = []
33
+ aggregate_incidents: list[Any] = []
34
+ anacredit_holders: list[Any] = []
35
+ anacredit_risks: list[Any] = []
36
+ anacredit_incidents: list[Any] = []
37
+ warnings: list[str] = []
38
+
39
+ def is_accepted(self) -> bool:
40
+ return self.header is not None and self.header.is_accepted()
41
+
42
+ def result_code(self) -> str | None:
43
+ return self.header.result_code if self.header else None
44
+
45
+ def records_for_person_code(self, person_code: str) -> list[Any]:
46
+ records = []
47
+ for collection in (
48
+ self.aggregates,
49
+ self.aggregate_incidents,
50
+ self.anacredit_holders,
51
+ self.anacredit_risks,
52
+ self.anacredit_incidents,
53
+ ):
54
+ records.extend(r for r in collection if r.person_code == person_code)
55
+ return records
56
+
57
+ def to_array(self) -> dict:
58
+ return {
59
+ 'header': self.header.to_array() if self.header else None,
60
+ 'is_accepted': self.is_accepted(),
61
+ 'result_code': self.result_code(),
62
+ 'legal_entity_errors': len(self.legal_entity_errors),
63
+ 'individual_errors': len(self.individual_errors),
64
+ 'legal_entity_assignments': len(self.legal_entity_assignments),
65
+ 'individual_assignments': len(self.individual_assignments),
66
+ 'aggregates': len(self.aggregates),
67
+ 'aggregate_incidents': len(self.aggregate_incidents),
68
+ 'anacredit_holders': len(self.anacredit_holders),
69
+ 'anacredit_risks': len(self.anacredit_risks),
70
+ 'anacredit_incidents': len(self.anacredit_incidents),
71
+ 'warnings': self.warnings,
72
+ }
@@ -0,0 +1,129 @@
1
+ from __future__ import annotations
2
+
3
+ from cirbe.cirbe_file import CirbeFile
4
+ from cirbe.exceptions import ValidationException
5
+ from cirbe.factories.record_factory import RecordFactory
6
+ from cirbe.models.request.individual_with_code_request_record import (
7
+ IndividualWithCodeRequestRecord,
8
+ )
9
+ from cirbe.models.request.individual_without_code_request_record import (
10
+ IndividualWithoutCodeRequestRecord,
11
+ )
12
+ from cirbe.models.request.legal_entity_with_code_request_record import (
13
+ LegalEntityWithCodeRequestRecord,
14
+ )
15
+ from cirbe.models.request.legal_entity_without_code_request_record import (
16
+ LegalEntityWithoutCodeRequestRecord,
17
+ )
18
+ from cirbe.models.request.request_header_record import RequestHeaderRecord
19
+ from cirbe.models.request.text_record import TextRecord
20
+ from cirbe.support.fixed_width_record import FixedWidthRecord
21
+
22
+ RECORD_LENGTH = FixedWidthRecord.RECORD_LENGTH
23
+
24
+
25
+ class CirbeService:
26
+ def __init__(self) -> None:
27
+ self._factory = RecordFactory()
28
+
29
+ @property
30
+ def factory(self) -> RecordFactory:
31
+ return self._factory
32
+
33
+ def generate_request_file(
34
+ self,
35
+ header: RequestHeaderRecord,
36
+ text: TextRecord,
37
+ legal_with_code: list[LegalEntityWithCodeRequestRecord] | None = None,
38
+ individual_with_code: list[IndividualWithCodeRequestRecord] | None = None,
39
+ legal_without_code: list[LegalEntityWithoutCodeRequestRecord] | None = None,
40
+ individual_without_code: list[IndividualWithoutCodeRequestRecord] | None = None,
41
+ line_ending: str = '\r\n',
42
+ ) -> str:
43
+ """Genera el fichero de petición CIRBE como string Unicode.
44
+
45
+ Para escribirlo a disco usar: open('fichero.txt', 'w', encoding='latin-1').
46
+ """
47
+ legal_with_code = legal_with_code or []
48
+ individual_with_code = individual_with_code or []
49
+ legal_without_code = legal_without_code or []
50
+ individual_without_code = individual_without_code or []
51
+
52
+ self._validate_no_duplicates(legal_with_code + individual_with_code)
53
+
54
+ all_records: list[FixedWidthRecord] = [
55
+ header,
56
+ text,
57
+ *legal_with_code,
58
+ *individual_with_code,
59
+ *legal_without_code,
60
+ *individual_without_code,
61
+ ]
62
+
63
+ all_errors: list[str] = []
64
+ for record in all_records:
65
+ all_errors.extend(record.validate())
66
+
67
+ if all_errors:
68
+ raise ValidationException(all_errors)
69
+
70
+ holder_count = (
71
+ len(legal_with_code)
72
+ + len(individual_with_code)
73
+ + len(legal_without_code)
74
+ + len(individual_without_code)
75
+ )
76
+ if holder_count == 0:
77
+ raise ValidationException(
78
+ ['Al menos un registro de petición (AI002, AI003, AI004 o AI005) es obligatorio']
79
+ )
80
+
81
+ content = ''
82
+ for record in all_records:
83
+ content += record.serialize() + line_ending
84
+
85
+ return self._normalize_lengths(content, line_ending)
86
+
87
+ def _normalize_lengths(self, content: str, line_ending: str) -> str:
88
+ result = ''
89
+ for line in content.split(line_ending):
90
+ if not line:
91
+ continue
92
+ line += line_ending
93
+ # Medir longitud en bytes latin-1 (Ñ = 1 byte) para calcular padding correcto
94
+ iso = line.encode('latin-1', errors='replace')
95
+ ending_bytes = line_ending.encode('latin-1')
96
+ line_len = len(iso) - len(ending_bytes)
97
+ padding = RECORD_LENGTH - line_len
98
+ if padding > 0:
99
+ iso = iso[: len(iso) - len(ending_bytes)] + b' ' * padding + ending_bytes
100
+ result += iso.decode('latin-1')
101
+ return result
102
+
103
+ def _validate_no_duplicates(self, with_code_records: list[FixedWidthRecord]) -> None:
104
+ seen: set[str] = set()
105
+ duplicates: set[str] = set()
106
+
107
+ for record in with_code_records:
108
+ code = record.person_code or ''
109
+ if not code:
110
+ continue
111
+ if code in seen:
112
+ duplicates.add(code)
113
+ seen.add(code)
114
+
115
+ if duplicates:
116
+ raise ValidationException([
117
+ 'Códigos duplicados en la petición: '
118
+ + ', '.join(sorted(duplicates))
119
+ + '. El Banco de España rechazará la petición (R5000).'
120
+ ])
121
+
122
+ def parse_response_file(self, content: str | bytes) -> CirbeFile:
123
+ """Parsea un fichero de respuesta CIRBE.
124
+
125
+ Acepta str (Unicode) o bytes (se decodifican como latin-1).
126
+ """
127
+ if isinstance(content, bytes):
128
+ content = content.decode('latin-1')
129
+ return self._factory.parse_file(content)
@@ -0,0 +1,47 @@
1
+ from .base import CirbeEnum
2
+ from .currency import CurrencyEnum
3
+ from .gender import GenderEnum
4
+ from .guarantee_coverage import GuaranteeCoverageEnum
5
+ from .header_result_code import HeaderResultCodeEnum
6
+ from .holder_error_code import HolderErrorCodeEnum
7
+ from .identifier_type import IdentifierTypeEnum
8
+ from .incident_type import IncidentTypeEnum
9
+ from .institutional_sector import InstitutionalSectorEnum
10
+ from .instrument_type import InstrumentTypeEnum
11
+ from .intervention_nature import InterventionNatureEnum
12
+ from .legal_form import LegalFormEnum
13
+ from .notification_code import NotificationCodeEnum
14
+ from .personal_guarantee_type import PersonalGuaranteeTypeEnum
15
+ from .person_nature import PersonNatureEnum
16
+ from .product_type import ProductTypeEnum
17
+ from .real_guarantee_type import RealGuaranteeTypeEnum
18
+ from .request_reason import RequestReasonEnum
19
+ from .residual_term import ResidualTermEnum
20
+ from .situation import SituationEnum
21
+ from .solidarity_type import SolidarityTypeEnum
22
+ from .street_type import StreetTypeEnum
23
+
24
+ __all__ = [
25
+ 'CirbeEnum',
26
+ 'CurrencyEnum',
27
+ 'GenderEnum',
28
+ 'GuaranteeCoverageEnum',
29
+ 'HeaderResultCodeEnum',
30
+ 'HolderErrorCodeEnum',
31
+ 'IdentifierTypeEnum',
32
+ 'IncidentTypeEnum',
33
+ 'InstitutionalSectorEnum',
34
+ 'InstrumentTypeEnum',
35
+ 'InterventionNatureEnum',
36
+ 'LegalFormEnum',
37
+ 'NotificationCodeEnum',
38
+ 'PersonalGuaranteeTypeEnum',
39
+ 'PersonNatureEnum',
40
+ 'ProductTypeEnum',
41
+ 'RealGuaranteeTypeEnum',
42
+ 'RequestReasonEnum',
43
+ 'ResidualTermEnum',
44
+ 'SituationEnum',
45
+ 'SolidarityTypeEnum',
46
+ 'StreetTypeEnum',
47
+ ]
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ from enum import Enum
4
+ from typing import Optional
5
+
6
+
7
+ class CirbeEnum(str, Enum):
8
+ """Base para todos los enums CIRBE: code/description/resolve."""
9
+
10
+ @classmethod
11
+ def extra_codes(cls) -> dict[str, str]:
12
+ return {}
13
+
14
+ def code(self) -> str:
15
+ return self.__class__.extra_codes().get(self.name, self.name)
16
+
17
+ def description(self) -> str:
18
+ return self.value
19
+
20
+ @classmethod
21
+ def resolve(cls, code: Optional[str]) -> Optional[CirbeEnum]:
22
+ if not code:
23
+ return None
24
+ code = code.strip()
25
+ try:
26
+ return cls[code]
27
+ except KeyError:
28
+ pass
29
+ for name, extra_code in cls.extra_codes().items():
30
+ if extra_code == code:
31
+ try:
32
+ return cls[name]
33
+ except KeyError:
34
+ pass
35
+ return None
36
+
37
+ @classmethod
38
+ def resolve_strict(cls, code: str) -> CirbeEnum:
39
+ result = cls.resolve(code)
40
+ if result is None:
41
+ raise ValueError(f'Código no válido para {cls.__name__}: {code}')
42
+ return result
43
+
44
+ @classmethod
45
+ def all(cls) -> list[dict[str, str]]:
46
+ extra = cls.extra_codes()
47
+ return [
48
+ {'code': extra.get(case.name, case.name), 'description': case.value}
49
+ for case in cls
50
+ ]
@@ -0,0 +1,19 @@
1
+ from .base import CirbeEnum
2
+
3
+
4
+ class CurrencyEnum(CirbeEnum):
5
+ EUR = 'Euro'
6
+ GBP = 'Libra esterlina'
7
+ SEK = 'Corona sueca'
8
+ DKK = 'Corona danesa'
9
+ NOK = 'Corona noruega'
10
+ USD = 'Dólar USA'
11
+ CAD = 'Dólar canadiense'
12
+ JPY = 'Yen'
13
+ CHF = 'Franco suizo'
14
+ ZY6 = 'No informable'
15
+ ZZY = 'No disponible'
16
+
17
+ @classmethod
18
+ def extra_codes(cls) -> dict[str, str]:
19
+ return {'OTHER_CURRENCY': '999'}
@@ -0,0 +1,6 @@
1
+ from .base import CirbeEnum
2
+
3
+
4
+ class GenderEnum(CirbeEnum):
5
+ C02 = 'Hombre'
6
+ C03 = 'Mujer'
@@ -0,0 +1,7 @@
1
+ from .base import CirbeEnum
2
+
3
+
4
+ class GuaranteeCoverageEnum(CirbeEnum):
5
+ E14 = 'Total'
6
+ E15 = 'Parcial'
7
+ ZZZ = 'No aplicable'