from http import HTTPStatus from flask_smorest import Blueprint, abort from marshmallow import Schema, fields from ..decorators import ensure_logged_in from ..models import Account from .. import decorators from .. import db_utils from .. import returns bp = Blueprint('accounts', __name__, description='Bank Accounts operations') VALID_CURRENCIES = ['RON', 'EUR', 'USD'] ACCOUNT_TYPES = ['Checking', 'Savings'] class MetaCurrenciesSchema(Schema): status = fields.Constant('success') currencies = fields.List(fields.Str()) class MetaAccountTypesSchema(Schema): status = fields.Constant('success') account_types = fields.List(fields.Str(), data_key='accountTypes') @bp.get('/meta/currencies') @bp.response(200, MetaCurrenciesSchema) def get_valid_currencies(): return returns.success(currencies=VALID_CURRENCIES) @bp.get('/meta/account_types') @bp.response(200, MetaAccountTypesSchema) def get_valid_account_types(): return returns.success(account_types=ACCOUNT_TYPES) @bp.get('/') @ensure_logged_in @bp.doc(security=[{'Token': []}]) def get_account_id(account_id: int): account = db_utils.get_account(account_id=account_id) if account is None: return returns.NOT_FOUND if decorators.user_id != db_utils.whose_account(account): return returns.UNAUTHORIZED account = account.to_json() return returns.success(account=account) @bp.get('/IBAN_') @ensure_logged_in @bp.doc(security=[{'Token': []}]) def get_account_iban(iban: str): account = db_utils.get_account(iban=iban) if account is None: return returns.NOT_FOUND if decorators.user_id != db_utils.whose_account(account): return returns.UNAUTHORIZED account = account.to_json() return returns.success(account=account) class CreateAccountParams(Schema): currency = fields.String() account_type = fields.String(data_key='accountType') custom_name = fields.String(data_key='customName') @bp.post('/') @ensure_logged_in @bp.arguments(CreateAccountParams, as_kwargs=True) @bp.response(200, Account.Schema) @bp.response(HTTPStatus.UNPROCESSABLE_ENTITY, description='Invalid currency or account type') @bp.doc(security=[{'Token': []}]) def create_account(currency: str, account_type: str, custom_name: str): if currency not in VALID_CURRENCIES: abort(HTTPStatus.UNPROCESSABLE_ENTITY) if account_type not in ACCOUNT_TYPES: abort(HTTPStatus.UNPROCESSABLE_ENTITY) account = Account(-1, '', currency, account_type, custom_name or '') db_utils.insert_account(decorators.user_id, account) return account.to_json()