"""Logic for payment_term's templates handling.""" from marshmallow import ValidationError from abacus_account.constants.error import ERROR_PAYMENT_TERM_TEMPLATE_DOES_NOT_EXISTS from abacus_account.logic.account_payment_term import create_account_payment_term from abacus_account.models import Account from abacus_account.models import AccountPaymentTermTemplate from abacus_account.utils.format_error import validation_error from abacus_account.utils.validations import validate_currency_code def create_payment_terms_from_template(template_id, account_id): """Create payee, account_payee and account_payment_term by template.""" Account.get_by_id_or_error(account_id) template = AccountPaymentTermTemplate.get_by_id_or_error(template_id) payment_term_params = { 'account_id': account_id, 'currency_code': template.currency_code } payment_term_params.update(template.payment_terms) payment_term = create_account_payment_term(**payment_term_params) return payment_term def create_payment_term_from_template_by_currency_code( currency_code: str, account_id: int ) -> object: """Create an account_payment_term from payment_term_template by currency code. Args: currency_code (str): An alpha-3 iso currency code account_id (int): Id of an account Returns: A payment term record for an account. """ Account.get_by_id_or_error(account_id) try: template = get_payment_term_template_by_currency_code(currency_code) payment_term_params = { 'account_id': account_id, 'currency_code': template.currency_code } payment_term_params.update(template.payment_terms) payment_term = create_account_payment_term(**payment_term_params) except Exception as e: status_code = e.kwargs.get('status_code', 400) \ if isinstance(e, ValidationError) else 400 return validation_error(str(e), status_code=status_code) return payment_term def get_payment_term_template_by_currency_code(currency_code: str) -> object: """Get payment term template by currency code. Args: currency_code (str): An alpha-3 iso currency code Returns: A payment term template for a specified currency code. """ validate_currency_code(currency_code) template = AccountPaymentTermTemplate.get_by_currency_code(currency_code) if template is None: raise ValidationError( message=ERROR_PAYMENT_TERM_TEMPLATE_DOES_NOT_EXISTS.format( currency_code=currency_code ), status_code=400 ) return template