Files
FirstCore/app/api/services/transaction_service.py
2025-05-28 13:14:09 +01:00

103 lines
3.5 KiB
Python

import logging
from datetime import datetime
from flask import jsonify
from app.models.transaction import Transaction
logger = logging.getLogger(__name__)
class TransactionService:
"""
Service class for handling transaction-related operations.
"""
@staticmethod
def process_request(filters=None):
"""
Process the get transactions request.
Args:
filters (dict, optional): Filters for the transactions query.
Returns:
dict: A standardized response with transactions data.
"""
try:
if filters is None:
filters = {}
# Extract filters
account_id = filters.get('account_id')
transaction_id = filters.get('transaction_id')
transaction_type = filters.get('type')
channel = filters.get('channel')
start_date = filters.get('start_date')
end_date = filters.get('end_date')
# Extract pagination parameters
page = int(filters.get('page', 1))
limit = int(filters.get('limit', 20))
# Ensure page and limit are valid
if page < 1:
page = 1
if limit < 1 or limit > 100:
limit = 20
# Convert string dates to datetime objects if provided
if start_date and isinstance(start_date, str):
start_date = datetime.fromisoformat(start_date.replace('Z', '+00:00'))
if end_date and isinstance(end_date, str):
end_date = datetime.fromisoformat(end_date.replace('Z', '+00:00'))
# Get transactions with optional filters and pagination
transactions, total_count = Transaction.get_all_transactions(
account_id=account_id,
transaction_id=transaction_id,
transaction_type=transaction_type,
channel=channel,
start_date=start_date,
end_date=end_date,
page=page,
limit=limit
)
# Convert transactions to dictionary format
transactions_data = []
for transaction in transactions:
transactions_data.append({
'id': transaction.id,
'transaction_id': transaction.transaction_id,
'account_id': transaction.account_id,
'type': transaction.type,
'customer_id': transaction.customer_id,
'channel': transaction.channel,
'created_at': transaction.created_at.isoformat(),
'updated_at': transaction.updated_at.isoformat()
})
# Calculate total pages
total_pages = (total_count + limit - 1) // limit
response_data = {
'transactions': transactions_data,
'count': len(transactions_data),
'pagination': {
'total_count': total_count,
'total_pages': total_pages,
'current_page': page,
'limit': limit,
'has_next': page < total_pages,
'has_prev': page > 1
}
}
return response_data
except Exception as e:
logger.error(f"An error occurred: {str(e)}", exc_info=True)
return jsonify({
"message": "Internal Server Error"
}), 500