forked from DigiFi/digifi-BankToProductCore
91 lines
3.0 KiB
Python
91 lines
3.0 KiB
Python
from datetime import datetime, timezone
|
|
from sqlalchemy.orm import relationship
|
|
#
|
|
# from app.api.services.offer_analysis import logger
|
|
from app.extensions import db
|
|
from app.models.account import Account
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.sql import func
|
|
# from app.utils.logger import logger
|
|
|
|
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(timezone=True), server_default=func.now())
|
|
updated_at = db.Column(db.DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
|
|
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",
|
|
)
|
|
|
|
transaction_offers = relationship(
|
|
"TransactionOffer",
|
|
primaryjoin="Customer.id == TransactionOffer.customer_id",
|
|
foreign_keys="TransactionOffer.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 customer
|
|
|
|
@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 ID '{id}' already exists.")
|
|
elif Account.query.filter_by(id=account_id).first():
|
|
raise ValueError(f"Account ID '{account_id}' already exists.")
|
|
elif cls.query.filter_by(msisdn=msisdn).first():
|
|
raise ValueError("MSISDN '{msisdn}' already exists")
|
|
|
|
# Create the customer
|
|
customer = cls(
|
|
id=id,
|
|
msisdn=msisdn,
|
|
country_code=country_code,
|
|
created_at=datetime.now(timezone.utc),
|
|
updated_at=datetime.now(timezone.utc)
|
|
)
|
|
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_with_loan_list(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}>'
|