91 lines
2.9 KiB
Python
91 lines
2.9 KiB
Python
from datetime import datetime, timezone
|
|
from app.extensions import db
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy import and_, or_, not_
|
|
|
|
|
|
class Transaction(db.Model):
|
|
__tablename__ = 'transactions'
|
|
id = db.Column(
|
|
db.Integer,
|
|
primary_key=True,
|
|
autoincrement=True,
|
|
)
|
|
# id = db.Column(db.Int, primary_key=True)
|
|
transaction_id = db.Column(db.String(50), nullable=False)
|
|
account_id = db.Column(db.String(50), nullable=False)
|
|
type = db.Column(db.String(50), nullable=False)
|
|
channel = db.Column(db.String(50), 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))
|
|
|
|
def __repr__(self):
|
|
return f'<Transaction {self.id}>'
|
|
|
|
@classmethod
|
|
def create_transaction(cls, transaction_id, account_id, type, channel):
|
|
|
|
# if cls.query.filter_by(transaction_id=transaction_id).first():
|
|
# raise ValueError("Duplicate Transaction")
|
|
|
|
if cls.query.filter(and_(cls.transaction_id == transaction_id, cls.type == type)).first():
|
|
raise ValueError("Duplicate Transaction")
|
|
|
|
transaction = cls(
|
|
transaction_id=transaction_id,
|
|
account_id=account_id,
|
|
type=type,
|
|
channel=channel
|
|
)
|
|
|
|
try:
|
|
db.session.add(transaction)
|
|
db.session.commit()
|
|
except IntegrityError as err:
|
|
db.session.rollback()
|
|
raise ValueError(f"Database integrity error: {err}")
|
|
|
|
return transaction
|
|
|
|
@classmethod
|
|
def get_transaction_by_id(cls, transaction_id):
|
|
return cls.query.get(transaction_id)
|
|
|
|
@classmethod
|
|
def get_all_transactions(cls, account_id=None, transaction_type=None, channel=None, start_date=None, end_date=None):
|
|
"""
|
|
Get all transactions with optional filtering
|
|
|
|
Args:
|
|
account_id (str, optional): Filter by account ID
|
|
transaction_type (str, optional): Filter by transaction type
|
|
channel (str, optional): Filter by channel
|
|
start_date (datetime, optional): Filter by start date
|
|
end_date (datetime, optional): Filter by end date
|
|
|
|
Returns:
|
|
list: List of Transaction objects
|
|
"""
|
|
query = cls.query
|
|
|
|
# Apply filters if provided
|
|
if account_id:
|
|
query = query.filter(cls.account_id == account_id)
|
|
|
|
if transaction_type:
|
|
query = query.filter(cls.type == transaction_type)
|
|
|
|
if channel:
|
|
query = query.filter(cls.channel == channel)
|
|
|
|
if start_date:
|
|
query = query.filter(cls.created_at >= start_date)
|
|
|
|
if end_date:
|
|
query = query.filter(cls.created_at <= end_date)
|
|
|
|
# Order by created_at descending (newest first)
|
|
query = query.order_by(cls.created_at.desc())
|
|
|
|
return query.all()
|