transdesk-importer-python-sdk 1.0.0__py3-none-any.whl

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 (28) hide show
  1. transdesk/importer/__init__.py +70 -0
  2. transdesk/importer/client.py +42 -0
  3. transdesk/importer/exporters/__init__.py +3 -0
  4. transdesk/importer/exporters/json_exporter.py +25 -0
  5. transdesk/importer/models/__init__.py +59 -0
  6. transdesk/importer/models/canonical.py +124 -0
  7. transdesk/importer/models/internal.py +182 -0
  8. transdesk/importer/readers/__init__.py +3 -0
  9. transdesk/importer/readers/excel_reader.py +77 -0
  10. transdesk/importer/shared/__init__.py +3 -0
  11. transdesk/importer/shared/data_normalizer.py +47 -0
  12. transdesk/importer/transformers/__init__.py +0 -0
  13. transdesk/importer/transformers/canonical/__init__.py +5 -0
  14. transdesk/importer/transformers/canonical/apolice_builder.py +272 -0
  15. transdesk/importer/transformers/canonical/cobertura_builder.py +39 -0
  16. transdesk/importer/transformers/canonical/item_classifier.py +22 -0
  17. transdesk/importer/transformers/internal/__init__.py +6 -0
  18. transdesk/importer/transformers/internal/coverage_mapper.py +138 -0
  19. transdesk/importer/transformers/internal/internal_mapper.py +176 -0
  20. transdesk/importer/transformers/internal/rcf_parser.py +47 -0
  21. transdesk/importer/transformers/internal/towing_parser.py +13 -0
  22. transdesk/importer/validators/__init__.py +3 -0
  23. transdesk/importer/validators/internal_policy_validator.py +75 -0
  24. transdesk_importer_python_sdk-1.0.0.dist-info/METADATA +228 -0
  25. transdesk_importer_python_sdk-1.0.0.dist-info/RECORD +28 -0
  26. transdesk_importer_python_sdk-1.0.0.dist-info/WHEEL +5 -0
  27. transdesk_importer_python_sdk-1.0.0.dist-info/licenses/LICENSE +21 -0
  28. transdesk_importer_python_sdk-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,13 @@
1
+ import re
2
+
3
+
4
+ class TowingParser:
5
+
6
+ def parse(self, produto):
7
+ produto = produto or ""
8
+ match = re.search(r"(\d+)", produto)
9
+
10
+ if not match:
11
+ return 0
12
+
13
+ return int(match.group(1))
@@ -0,0 +1,3 @@
1
+ from .internal_policy_validator import InternalPolicyValidator
2
+
3
+ __all__ = ["InternalPolicyValidator"]
@@ -0,0 +1,75 @@
1
+ from dataclasses import asdict
2
+
3
+ from transdesk.importer.models.internal import ValidationError
4
+
5
+
6
+ class InternalPolicyValidator:
7
+
8
+ def validate(self, canonical_policies, internal_policies):
9
+ errors = []
10
+
11
+ if len(canonical_policies) != len(internal_policies):
12
+ errors.append(ValidationError(
13
+ type="policy_count",
14
+ canonical=len(canonical_policies),
15
+ internal=len(internal_policies),
16
+ ))
17
+
18
+ for canonical, internal in zip(canonical_policies, internal_policies):
19
+ self._validate_policy(canonical, internal, errors)
20
+
21
+ return errors
22
+
23
+ def _validate_policy(self, canonical, internal, errors):
24
+ canonical_items = canonical.itens
25
+ internal_items = internal.data.items
26
+
27
+ if len(canonical_items) != len(internal_items):
28
+ errors.append(ValidationError(
29
+ policy=canonical.cod_agrupador_apolice,
30
+ type="item_count",
31
+ canonical=len(canonical_items),
32
+ internal=len(internal_items),
33
+ ))
34
+
35
+ for index, (canonical_item, internal_item) in enumerate(
36
+ zip(canonical_items, internal_items), start=1
37
+ ):
38
+ self._validate_item(
39
+ canonical.cod_agrupador_apolice,
40
+ index,
41
+ canonical_item,
42
+ internal_item,
43
+ errors,
44
+ )
45
+
46
+ def _validate_item(self, policy_id, item_number, canonical_item, internal_item, errors):
47
+ canonical_premium = self._calculate_canonical_premium(canonical_item)
48
+ internal_premium = self._calculate_internal_premium(internal_item)
49
+
50
+ if round(canonical_premium, 2) != round(internal_premium, 2):
51
+ errors.append(ValidationError(
52
+ policy=policy_id,
53
+ item=item_number,
54
+ type="premium",
55
+ canonical=canonical_premium,
56
+ internal=internal_premium,
57
+ difference=(canonical_premium - internal_premium),
58
+ ))
59
+
60
+ def _calculate_canonical_premium(self, canonical_item):
61
+ total = 0
62
+
63
+ for coverage in canonical_item.coberturas:
64
+ total += (coverage.valor_mensalidade or 0)
65
+
66
+ return total
67
+
68
+ def _calculate_internal_premium(self, internal_item):
69
+ total = 0
70
+
71
+ for key, value in asdict(internal_item).items():
72
+ if key.endswith("_premium"):
73
+ total += (value or 0)
74
+
75
+ return total
@@ -0,0 +1,228 @@
1
+ Metadata-Version: 2.4
2
+ Name: transdesk-importer-python-sdk
3
+ Version: 1.0.0
4
+ Summary: SDK de leitura/transformacao de planilhas de apolices Transdesk para o formato interno 77seg
5
+ Author-email: FMConsult <contato@fmconsult.com.br>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 FMConsult
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/fmconsult/77seg-transdesk-importer
29
+ Project-URL: Bug Tracker, https://github.com/fmconsult/77seg-transdesk-importer/issues
30
+ Keywords: sdk,transdesk,importer,apolices,77seg
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Operating System :: OS Independent
34
+ Requires-Python: >=3.11
35
+ Description-Content-Type: text/markdown
36
+ License-File: LICENSE
37
+ Requires-Dist: pandas>=2.0
38
+ Requires-Dist: openpyxl>=3.1
39
+ Requires-Dist: xlrd>=2.0
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest>=7.0; extra == "dev"
42
+ Dynamic: license-file
43
+
44
+ # transdesk-importer-python-sdk
45
+
46
+ SDK Python para leitura e transformacao de planilhas de apolices da **Transdesk**
47
+ no formato interno consumido pela `77seg-core-api`.
48
+
49
+ O SDK e **puro**: ele apenas **le, transforma e valida** a planilha, devolvendo
50
+ modelos tipados. Ele **nao** grava no banco, nao cadastra leads/corretoras e nao
51
+ gera link de assinatura -- essas responsabilidades ficam na core-api
52
+ (ver [Referencia de enrichment](#referencia-de-enrichment-core-api)).
53
+
54
+ ## Instalacao
55
+
56
+ ```bash
57
+ pip install transdesk-importer-python-sdk
58
+ ```
59
+
60
+ Requer Python >= 3.11.
61
+
62
+ ## Uso
63
+
64
+ A entrada pode ser `bytes` (upload em memoria), um objeto file-like binario ou
65
+ um caminho de arquivo. O formato (`.xls`/`.xlsx`) e detectado automaticamente
66
+ por magic bytes -- nao depende da extensao.
67
+
68
+ ```python
69
+ from transdesk.importer import TransdeskImporter
70
+
71
+ # 1) a partir de bytes (ex.: upload de um endpoint)
72
+ file_bytes = request.files["file"].file.read()
73
+ result = TransdeskImporter().import_policies(file_bytes)
74
+
75
+ # 2) a partir de um caminho
76
+ result = TransdeskImporter().import_policies("apolices.xls")
77
+
78
+ if not result.is_valid:
79
+ # result.errors -> list[ValidationError]
80
+ for err in result.errors:
81
+ print(err)
82
+ else:
83
+ for policy in result.policies: # list[InternalPolicy]
84
+ print(policy.reference_id, len(policy.data.items))
85
+
86
+ # serializacao pronta para JSON
87
+ payload = result.to_dict() # dict
88
+ as_json = result.to_json() # str (ensure_ascii=False)
89
+ ```
90
+
91
+ ## Retorno
92
+
93
+ `import_policies(file)` devolve um `ImportResult`:
94
+
95
+ | Campo | Tipo | Descricao |
96
+ | ---------- | ----------------------- | ------------------------------------------ |
97
+ | `policies` | `list[InternalPolicy]` | Apolices ja no formato interno |
98
+ | `errors` | `list[ValidationError]` | Divergencias encontradas na validacao |
99
+ | `is_valid` | `bool` | `True` quando `errors` esta vazio |
100
+
101
+ Helpers: `result.to_dict()` e `result.to_json(**kwargs)`.
102
+
103
+ ### Principais modelos
104
+
105
+ - Saida (EN): `InternalPolicy`, `PolicyData`, `ResellerData`, `Broker`, `Lead`,
106
+ `CustomerInfo`, `Telephone`, `Mobile`, `Address`, `InternalItem`.
107
+ - Canonico (PT, em `InternalPolicy.original_data`): `CanonicalPolicy`,
108
+ `CanonicalItem`, `Subestipulante`, `Cliente`, `Endereco`, `DadosBancarios`,
109
+ `UnidadeVenda`, `Cobertura`, `Complemento`.
110
+
111
+ `InternalItem` tem um schema "achatado" e **consistente**: todos os campos de
112
+ cobertura e de risco estao sempre presentes; os que nao se aplicam ao tipo do
113
+ item (ex.: campos de vida num veiculo) vem como `null`.
114
+
115
+ ### Validacao
116
+
117
+ O `ValidationError` cobre tres tipos:
118
+
119
+ - `policy_count` -- divergencia na contagem de apolices;
120
+ - `item_count` -- divergencia na contagem de itens de uma apolice;
121
+ - `premium` -- divergencia (apos arredondamento) entre o premio somado no
122
+ canonico e o premio somado no formato interno de um item.
123
+
124
+ ## Arquitetura
125
+
126
+ ```
127
+ planilha (bytes/file-like/path)
128
+ |
129
+ v
130
+ ExcelReader -> DataFrame
131
+ |
132
+ v
133
+ ApoliceBuilder -> list[CanonicalPolicy] (camada canonica, PT)
134
+ |
135
+ v
136
+ InternalMapper -> list[InternalPolicy] (camada interna, EN)
137
+ |
138
+ v
139
+ InternalPolicyValidator-> list[ValidationError]
140
+ |
141
+ v
142
+ ImportResult (policies + errors)
143
+ ```
144
+
145
+ ## Desenvolvimento
146
+
147
+ ```bash
148
+ python -m venv venv && source venv/bin/activate
149
+ pip install -e ".[dev]"
150
+ pytest
151
+ ```
152
+
153
+ Publicacao: criar uma tag `vX.Y.Z` dispara o workflow de publish no PyPI
154
+ (`.github/workflows/publish.yml`).
155
+
156
+ ## Referencia de enrichment (core-api)
157
+
158
+ > Esta secao **nao** faz parte do SDK. Ela preserva, como referencia, a logica
159
+ > de "enrichment" e persistencia que **saiu** do importer e deve ser portada
160
+ > para a `77seg-core-api`.
161
+
162
+ Apos obter as `InternalPolicy` do SDK, a core-api deve:
163
+
164
+ 1. **Completar os dados** de cada apolice (cadastrar lead e unidade/corretora,
165
+ injetar `enterprise_id`/`reseller_id` e os defaults da venda);
166
+ 2. **Persistir** os registros das vendas no banco;
167
+ 3. **Gerar o link de assinatura** (Paperless) e atualizar o status para
168
+ `pending_signature`.
169
+
170
+ Codigo original (removido do SDK), que serve de base para a implementacao na
171
+ core-api:
172
+
173
+ ```python
174
+ class InternalImportPipeline:
175
+
176
+ def __init__(self, enterprise_id, reseller_id):
177
+ self.enterprise_id = enterprise_id
178
+ self.reseller_id = reseller_id
179
+
180
+ def execute(self, policies):
181
+ policies = [self._complete_data(policy) for policy in policies]
182
+ policies = self._create_db_records(policies)
183
+ policies = self._generate_signature_link(policies)
184
+ return policies
185
+
186
+ def _complete_data(self, policy):
187
+ lead = policy.get('data').get('lead')
188
+ # TODO: gerar o cadastro do lead no BD
189
+
190
+ broker = policy.get('data').get('reseller').get('broker')
191
+ # TODO: gerar o cadastro da unidade (corretora) no BD
192
+ # TODO: gerar o cadastro do vendedor padrao da unidade (corretora) no BD
193
+
194
+ # preencher os dados faltantes
195
+ policy.update({
196
+ 'enterprise': {'id': self.enterprise_id},
197
+ 'reseller': {'id': self.reseller_id, 'person': broker},
198
+ 'lead': lead,
199
+ 'status': 'quotation_completed',
200
+ 'payment_method': 'bank_slip',
201
+ 'multi': True,
202
+ 'active': True,
203
+ 'deleted': False
204
+ })
205
+ return policy
206
+
207
+ def _create_db_records(self, policies):
208
+ # TODO: insere os registros no BD
209
+ return policies
210
+
211
+ def _generate_signature_link(self, policies):
212
+ # TODO: gera o link de assinatura (via Paperless) para cada venda
213
+ # TODO: atualiza o status da venda p/ pending_signature
214
+ return policies
215
+ ```
216
+
217
+ Ponto de integracao na core-api (esboco):
218
+
219
+ ```python
220
+ from transdesk.importer import TransdeskImporter
221
+
222
+ result = TransdeskImporter().import_policies(file_bytes)
223
+ if not result.is_valid:
224
+ ... # retornar result.errors
225
+
226
+ policies = [p.to_dict() if hasattr(p, "to_dict") else p for p in result.policies]
227
+ # aplicar _complete_data / _create_db_records / _generate_signature_link aqui
228
+ ```
@@ -0,0 +1,28 @@
1
+ transdesk/importer/__init__.py,sha256=6nf9-HeOgrulFPQxFDYcNKd6Y5X_2pTtO8dI2RmxwVs,1435
2
+ transdesk/importer/client.py,sha256=rHzptkSn7agaPunSZLkVuPGTjRmSUWCzhUk4Mk68BAY,1569
3
+ transdesk/importer/exporters/__init__.py,sha256=XXU75zMDpCp2h6fqUMSdGfhUWCGntY17FZwXlEsxUO0,68
4
+ transdesk/importer/exporters/json_exporter.py,sha256=mMa5p42jo42p5E5MxllKLj-lfzEIkslLoZiLH67jReQ,787
5
+ transdesk/importer/models/__init__.py,sha256=soABNzXnVo956_CnTb2N5YouIBT51nx-KeznUyDd2NE,979
6
+ transdesk/importer/models/canonical.py,sha256=3XWBOeS34i6_dZYkrybWeuBGhzXTvDSVLm0lDOV-yoQ,3198
7
+ transdesk/importer/models/internal.py,sha256=5TezR_ZqxKzBWlQs2BE7ws7RX0XTfM4qqY4vPx4pzoU,4298
8
+ transdesk/importer/readers/__init__.py,sha256=bBObYifSLerg5GEdwV_So7G355YfofM5LgtYryz4WGo,125
9
+ transdesk/importer/readers/excel_reader.py,sha256=_PQE6qpKCrbNRzw0Ij2gbmdGcpIoEYs61FvLuZJJD5k,2330
10
+ transdesk/importer/shared/__init__.py,sha256=DFisoxirzEy5T6xQCYVRv4b_CSyYxpI8turMqyD1imE,74
11
+ transdesk/importer/shared/data_normalizer.py,sha256=1FVdSevmt61dJFePh49sAJ28Y29t_5IrGWIkUrsRqwE,993
12
+ transdesk/importer/transformers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ transdesk/importer/transformers/canonical/__init__.py,sha256=VEgS-NX_Dj2gJSPbSprZLTGTpQ-kZxRCP-61xLlKWd0,204
14
+ transdesk/importer/transformers/canonical/apolice_builder.py,sha256=FtAmvYp0tugy5LXuFdPmZ9EpFqPZphqKUcCWQmRkKuM,8812
15
+ transdesk/importer/transformers/canonical/cobertura_builder.py,sha256=7fR7HJjW605J_TkYD3dmg67fPh65-dB4knRgumVDTkg,1371
16
+ transdesk/importer/transformers/canonical/item_classifier.py,sha256=HTuEqwTTm82CQFy5qt966RyIAehgJWQDvaB0IqTt3z0,517
17
+ transdesk/importer/transformers/internal/__init__.py,sha256=tkWbDHd_EeCZ_eUeXDJa4DfcOPlYadbam9KusiwLUek,239
18
+ transdesk/importer/transformers/internal/coverage_mapper.py,sha256=nj6vxM8vdbBlmdA5TGfXQR-D5qdUxKl80_5c3Z5wmF8,4677
19
+ transdesk/importer/transformers/internal/internal_mapper.py,sha256=H9DcfOdbMY7i8uysG3WAiG_L5cYbsTicz3GTaL9pzGQ,5092
20
+ transdesk/importer/transformers/internal/rcf_parser.py,sha256=0H93sg5zl9OtA3EGeTeTGMmvh16ca2Pd-EkUqzhlvdo,1053
21
+ transdesk/importer/transformers/internal/towing_parser.py,sha256=pFf207O9Aya4zchfZR0o8bmuuP2otVKWXOJL7c49XgA,220
22
+ transdesk/importer/validators/__init__.py,sha256=jUoCZ4Zw33E86MbkltNItD3ljsnKAzFnILgHWOc7piw,102
23
+ transdesk/importer/validators/internal_policy_validator.py,sha256=P7BFEQjZAoVPn35vljxFAJwzHZ8hfwOwQcqKhARi6zM,2501
24
+ transdesk_importer_python_sdk-1.0.0.dist-info/licenses/LICENSE,sha256=9nhX2zixjTq8LCzy28lfTKJRo-ro7DibBvuv0BexpmI,1066
25
+ transdesk_importer_python_sdk-1.0.0.dist-info/METADATA,sha256=Vk9qVbgVPQoCNFDOT4Kj9alsznTYOFE-0mXQT_BZ4Uw,8190
26
+ transdesk_importer_python_sdk-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
27
+ transdesk_importer_python_sdk-1.0.0.dist-info/top_level.txt,sha256=TWPAu9KRvDN40kbqCQBedaeYnHkuwSg8RNDYg8GfIxU,10
28
+ transdesk_importer_python_sdk-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 FMConsult
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.