71 lines
2.2 KiB
Python
71 lines
2.2 KiB
Python
from datetime import datetime, timezone
|
|
from sqlalchemy.orm import relationship
|
|
from app.extensions import db
|
|
from app.models.account import Account
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
class Customer(db.Model):
|
|
__tablename__ = 'customers'
|
|
|
|
id = db.Column(db.String(50), primary_key=True)
|
|
msisdn = db.Column(db.String(20), unique=True, nullable=False)
|
|
country_code = db.Column(db.String(3), nullable=False)
|
|
created_at = db.Column(db.DateTime, default=datetime.now(timezone.utc))
|
|
updated_at = db.Column(db.DateTime, default=datetime.now(timezone.utc), onupdate=datetime.now(timezone.utc))
|
|
|
|
accounts = relationship(
|
|
"Account",
|
|
primaryjoin="Customer.id == Account.customer_id",
|
|
foreign_keys="Account.customer_id",
|
|
back_populates="customer",
|
|
)
|
|
|
|
loans = relationship(
|
|
"Loan",
|
|
primaryjoin="Customer.id == Loan.customer_id",
|
|
foreign_keys="Loan.customer_id",
|
|
back_populates="customer",
|
|
)
|
|
|
|
@classmethod
|
|
def is_valid_customer(cls, customer_id):
|
|
customer = cls.query.filter_by(id=customer_id).first()
|
|
if not customer:
|
|
return False
|
|
return True
|
|
|
|
@classmethod
|
|
def create_customer(cls, id, msisdn, country_code, account_id, account_type='savings'):
|
|
if cls.query.filter_by(id=id).first():
|
|
raise ValueError("Customer already exists")
|
|
|
|
# Create the customer
|
|
customer = cls(id=id, msisdn=msisdn, country_code=country_code)
|
|
try:
|
|
db.session.add(customer)
|
|
|
|
# Create an associated account
|
|
account = Account.create_account(
|
|
id=account_id,
|
|
customer_id=id,
|
|
account_type=account_type
|
|
)
|
|
|
|
except IntegrityError as err:
|
|
raise ValueError(f"Database integrity error: {err}")
|
|
return customer
|
|
|
|
@classmethod
|
|
def get_customer(cls, customer_id):
|
|
"""
|
|
Get customer by ID.
|
|
"""
|
|
customer = cls.query.filter_by(id=customer_id).first()
|
|
|
|
if not customer:
|
|
raise ValueError(f"Customer does not exist")
|
|
return customer
|
|
|
|
def __repr__(self):
|
|
return f'<Customer {self.id}>'
|