|
|
import json
|
|
|
from typing import List, Optional
|
|
|
from pydantic import BaseModel, Field, EmailStr, ValidationError
|
|
|
|
|
|
|
|
|
|
|
|
class Relation(BaseModel):
|
|
|
"""A Pydantic model for a single relation."""
|
|
|
citizen_id: str = Field(..., min_length=1)
|
|
|
relation_type: str = Field(..., min_length=1)
|
|
|
|
|
|
class Customer(BaseModel):
|
|
|
"""
|
|
|
A simplified and robust class to represent a customer using Pydantic.
|
|
|
Validation is handled automatically based on type hints.
|
|
|
"""
|
|
|
|
|
|
name: str = Field(..., min_length=1, description="Customer's full name.")
|
|
|
birth: int = Field(..., gt=0, description="Customer's birth must be a positive number.")
|
|
|
current_position: str = Field(..., min_length=1)
|
|
|
|
|
|
email: EmailStr
|
|
|
|
|
|
|
|
|
|
|
|
relations: List[Relation] = []
|
|
|
|
|
|
def save(self, filepath: str = "customers.jsonl"):
|
|
|
"""
|
|
|
Saves the customer data to a JSONL file.
|
|
|
Each customer is appended as a new line.
|
|
|
"""
|
|
|
try:
|
|
|
with open(filepath, 'a', encoding='utf-8') as f:
|
|
|
|
|
|
f.write(self.model_dump_json() + '\n')
|
|
|
print(f"✅ Successfully saved customer '{self.name}' to {filepath}")
|
|
|
except IOError as e:
|
|
|
print(f"❌ Error saving file: {e}")
|
|
|
|
|
|
def as_string(self) -> str:
|
|
|
"""Returns the customer data as a formatted string."""
|
|
|
return f"""
|
|
|
Customer Information:
|
|
|
Name: {self.name}
|
|
|
Birth: {self.birth}
|
|
|
Position: {self.current_position}
|
|
|
Email: {self.email}
|
|
|
Phone: {self.phone}
|
|
|
Relations:
|
|
|
{self.relations}
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
print("--- Attempting to create a valid customer ---")
|
|
|
try:
|
|
|
valid_customer = Customer(
|
|
|
name="Đảng Cộng sản Việt Nam",
|
|
|
birth=1930,
|
|
|
current_position="Đảng cầm quyền và là chính đảng duy nhất được phép hoạt động tại Việt Nam",
|
|
|
email="ngjabach@example.com",
|
|
|
)
|
|
|
print("Customer created successfully:")
|
|
|
print(valid_customer)
|
|
|
|
|
|
|
|
|
valid_customer.save()
|
|
|
|
|
|
except ValidationError as e:
|
|
|
print("Validation Error:", e)
|
|
|
|
|
|
print("\n" + "="*50 + "\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|