konecty-sdk-python 1.0.4__tar.gz → 1.0.5__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.
@@ -1,6 +1,8 @@
1
+ import json
1
2
  import re
2
3
  from datetime import datetime
3
- from typing import Any, Optional, Self
4
+ from decimal import Decimal
5
+ from typing import Any, Dict, List, Optional, Self
4
6
 
5
7
  from pydantic import BaseModel, Field
6
8
  from pydantic.json_schema import JsonSchemaValue
@@ -168,12 +170,98 @@ class KonectyUser(BaseModel):
168
170
  class KonectyBaseModel(BaseModel):
169
171
  """Modelo base para documentos do Konecty."""
170
172
 
171
- id: str = Field(alias="_id")
172
- created_at: KonectyDateTime = Field(alias="_createdAt")
173
- created_by: KonectyUser = Field(alias="_createdBy")
174
- updated_at: KonectyDateTime = Field(alias="_updatedAt")
175
- updated_by: KonectyUser = Field(alias="_updatedBy")
176
- user: list[KonectyUser] = Field(alias="_user")
173
+ class UserRef(BaseModel):
174
+ id: Optional[str] = Field(None, alias="_id")
175
+ name: Optional[str] = None
176
+ group: Optional[dict] = None
177
+ active: Optional[bool] = None
178
+
179
+ id: Optional[str] = Field(None, alias="_id")
180
+ code: Optional[int] = None
181
+ created_at: Optional[datetime] = Field(None, alias="_createdAt")
182
+ created_by: Optional[UserRef] = Field(None, alias="_createdBy")
183
+ updated_at: Optional[datetime] = Field(None, alias="_updatedAt")
184
+ updated_by: Optional[UserRef] = Field(None, alias="_updatedBy")
185
+ users: Optional[List[UserRef]] = Field(None, alias="_user")
186
+
187
+ model_config = {
188
+ "populate_by_name": True,
189
+ "json_encoders": {
190
+ datetime: lambda v: json.dumps({"$date": v.isoformat()}),
191
+ Decimal: lambda v: str(v),
192
+ },
193
+ "extra": "allow",
194
+ }
195
+
196
+ @classmethod
197
+ def from_json(cls, json_str: str) -> Self:
198
+ """Cria uma instância do modelo a partir de uma string JSON.
199
+
200
+ Args:
201
+ json_str: String JSON válida representando o objeto
202
+
203
+ Returns:
204
+ Uma instância do modelo
205
+
206
+ Raises:
207
+ ValueError: Se o JSON for inválido
208
+ ValidationError: Se os dados não corresponderem ao modelo
209
+ """
210
+ try:
211
+ data = json.loads(json_str)
212
+ return cls.from_dict(data)
213
+ except json.JSONDecodeError as e:
214
+ raise ValueError(f"JSON inválido: {str(e)}")
215
+
216
+ @classmethod
217
+ def from_dict(cls, data: Dict[str, Any]) -> Self:
218
+ """Cria uma instância do modelo a partir de um dicionário.
219
+
220
+ Args:
221
+ data: Dicionário com os dados do objeto
222
+
223
+ Returns:
224
+ Uma instância do modelo
225
+
226
+ Raises:
227
+ ValidationError: Se os dados não corresponderem ao modelo
228
+ """
229
+ return cls.model_validate(data)
230
+
231
+ def to_json(self, **kwargs) -> str:
232
+ """Converte o modelo para uma string JSON.
233
+
234
+ Args:
235
+ **kwargs: Argumentos adicionais para json.dumps
236
+
237
+ Returns:
238
+ String JSON representando o objeto
239
+ """
240
+ return json.dumps(self.to_dict(), **kwargs)
241
+
242
+ def to_dict(self) -> Dict[str, Any]:
243
+ """Converte o modelo para um dicionário.
244
+
245
+ Returns:
246
+ Dicionário representando o objeto
247
+ """
248
+ return self.model_dump(by_alias=True)
249
+
250
+ def to_update_dict(self) -> Dict[str, Any]:
251
+ """Converte o modelo para um dicionário de atualização.
252
+
253
+ Returns:
254
+ Dicionário representando o objeto
255
+ """
256
+ return {"_id": self.id, "_updatedAt": self.updated_at or datetime.now()}
257
+
258
+ def extend(self, data: Dict[str, Any]):
259
+ """Extende esse objeto, adcionando os dados recebidos"""
260
+ field_names = list(self.model_fields.keys())
261
+
262
+ for key, value in data.items():
263
+ if key in field_names:
264
+ setattr(self, key, value)
177
265
 
178
266
 
179
267
  class KonectyLabel(BaseModel):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: konecty_sdk_python
3
- Version: 1.0.4
3
+ Version: 1.0.5
4
4
  Summary: Konecty SDK Python
5
5
  Author-email: Leonardo Leal <leonardo.leal@konecty.com>, Derotino Silveira <derotino.silveira@konecty.com>
6
6
  License: MIT
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "konecty_sdk_python"
3
- version = "1.0.4"
3
+ version = "1.0.5"
4
4
  description = "Konecty SDK Python"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"