75 lines
3.0 KiB
Python
75 lines
3.0 KiB
Python
from datetime import datetime, timezone
|
|
from app.extensions import db
|
|
from app.utils.logger import logger
|
|
|
|
class RepaymentsData(db.Model):
|
|
__tablename__ = 'repayments_data'
|
|
|
|
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
|
|
transaction_id = db.Column(db.String(50), nullable=False)
|
|
added_date = db.Column(db.DateTime(timezone=True), default=datetime.now(timezone.utc), nullable=False)
|
|
response_code = db.Column(db.String(10), nullable=True)
|
|
response_descr = db.Column(db.String(255), nullable=True)
|
|
fbn_transaction_id = db.Column(db.String(255),nullable=True)
|
|
account_id = db.Column(db.String(50), nullable=True)
|
|
customer_id = db.Column(db.String(50), nullable=True)
|
|
repayment_amount = db.Column(db.Float, nullable=True)
|
|
amount_collected = db.Column(db.Float, nullable=True)
|
|
balance = db.Column(db.Float, nullable=True, default=0.0)
|
|
|
|
def to_dict(self):
|
|
return {
|
|
"id": self.id,
|
|
"transaction_id": self.transaction_id,
|
|
"added_date": self.added_date.isoformat() if self.added_date else None,
|
|
"response_code": self.response_code,
|
|
"response_descr": self.response_descr,
|
|
"customerId": self.customer_id,
|
|
"accountId": self.account_id,
|
|
"fbnTransactionId": self.fbn_transaction_id,
|
|
"repaymentAmount": self.repayment_amount,
|
|
"amountCollected": self.amount_collected,
|
|
"balance": self.balance
|
|
}
|
|
|
|
|
|
def __repr__(self):
|
|
return f"<RepaymentsData id={self.id}, transaction_id={self.transaction_id}>"
|
|
|
|
@classmethod
|
|
def add_repayment_data(cls, data):
|
|
"""
|
|
Add a new repayment data entry.
|
|
"""
|
|
try:
|
|
repayment_amount = float(data.get('repaymentAmount', 0.0))
|
|
amount_collected = float(data.get('amountCollected', 0.0))
|
|
|
|
if amount_collected < 0 or repayment_amount < 0:
|
|
raise ValueError("Amounts cannot be negative.")
|
|
|
|
account_balance = round(repayment_amount - amount_collected, 2)
|
|
|
|
new_data = cls(
|
|
transaction_id=data.get('transactionId'),
|
|
response_code=data.get('responseCode'),
|
|
response_descr=data.get('responseDescr'),
|
|
fbn_transaction_id=data.get('fbnTransactionId'),
|
|
account_id=data.get('accountId'),
|
|
customer_id=data.get('customerId'),
|
|
amount_collected=amount_collected,
|
|
repayment_amount=repayment_amount,
|
|
balance=account_balance,
|
|
)
|
|
|
|
db.session.add(new_data)
|
|
db.session.commit()
|
|
|
|
logger.info("Repayment data committed successfully")
|
|
return new_data
|
|
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
logger.error(f"Error adding repayment data: {e}")
|
|
raise Exception(f"Error adding repayment data: {str(e)}")
|
|
|