"""Logic for Worksheet Account Contract Closing Balance.""" from typing import Any, Dict, List from sqlalchemy import exc from payment import models from payment.constants import error from payment.constants.constants import REVENUE_TRANSACTION_TYPES from payment.logic.exceptions import LogicError from payment.models.worksheet_account_contract_closing_balance import ( WorksheetAccountContractClosingBalance, ) from payment.repository import worksheet_account_contract_closing_balance as repository from payment.utils.format_response import prepare_dataload_response def get_by_statement_period_id( statement_period_id: int, account_ids: List[int] = None, contract_ids: List[int] = None, limit: int = None, offset: int = None, ) -> Dict[str, Any]: """Get worksheet_account_contract_closing_balance by statement_period_id. Args: statement_period_id (int): id of the statement period """ items, total_count = ( WorksheetAccountContractClosingBalance.get_by_statement_period_id( statement_period_id=statement_period_id, account_ids=account_ids, contract_ids=contract_ids, limit=limit, offset=offset, ) ) return { 'items': items, 'total_count': total_count, } def get_by_ids( worksheet_closing_balance_ids: List[int] = None, limit: int = None, offset: int = None, ) -> Dict[str, Any]: """Get worksheet_account_contract_closing_balance by list of IDs.""" items, total_count = WorksheetAccountContractClosingBalance.get_by_ids( worksheet_closing_balance_ids=worksheet_closing_balance_ids, limit=limit, offset=offset, ) return {'items': items, 'total_count': total_count} def bulk_create( event_id: int, statement_period_id: int, payment_entity_id: int, create_params: tuple, ) -> List[WorksheetAccountContractClosingBalance]: """Create one or more worksheet_account_contract_closing_balance records. Args: event_id (int): id of the event statement_period_id (int): id of the statement period payment_entity_id (int): id of the payment entity create_params (tuple): POST parameters per record """ if not create_params: raise LogicError(error.ERROR_NO_INSTANCES_TO_CREATE) contracts = [record['contract_id'] for record in create_params] if len(contracts) != len(set(contracts)): raise LogicError(error.ERROR_CONTRACT_DUPLICATE) if WorksheetAccountContractClosingBalance.exists_active_for_statement_period_and_contracts( statement_period_id, contracts ): raise LogicError(error.ERROR_WORKSHEET_ALREADY_EXISTS) base_params = { 'abacus_event_id': event_id, 'statement_period_id': statement_period_id, 'reference_payment_entity_id': payment_entity_id, } instances = [ WorksheetAccountContractClosingBalance(**{**params, **base_params}) for params in create_params ] try: WorksheetAccountContractClosingBalance.bulk_create(instances) except exc.IntegrityError: raise LogicError(error.ERROR_INTEGRITY) return instances def bulk_delete(event_id: int) -> None: """Soft delete worksheet_account_contract_closing_balance. Args: event_id (int): id of the event """ WorksheetAccountContractClosingBalance.soft_delete_by_event_id(event_id) def dataload_by_payment_account_ids(ids: List[int]): """Get instances for the specified ids.""" instances_list = repository.get_closing_balances_related_to_payment_accounts(ids) result = prepare_dataload_response( ids, instances_list, 'payment_group_payment_account_id' ) return {'items': result} def bulk_copy_into_taxable_revenue_by_event_id(event_id: int): """Bulk copy from close balance entries to taxable revenue entries by event_id.""" close_balance_entities = ( WorksheetAccountContractClosingBalance.get_by_abacus_event_id(event_id) ) worksheet_account_contract_taxable_revenues = _create_worksheet_taxable_revenues( close_balance_entities ) try: models.WorksheetAccountContractTaxableRevenue.bulk_create( worksheet_account_contract_taxable_revenues ) except exc.IntegrityError: pass def _create_worksheet_taxable_revenues( worksheets: List[models.WorksheetAccountContractClosingBalance], ): """ Create WorksheetAccountContractTaxableRevenue based on parent instance. Populates the data using the WorksheetAccountContractClosingBalance """ taxable_revenues = [] for worksheet in worksheets: taxable_revenues.append( models.WorksheetAccountContractTaxableRevenue( worksheet_account_contract_closing_balance_id=worksheet.worksheet_account_contract_closing_balance_id, # noqa account_id=worksheet.account_id, contract_id=worksheet.contract_id, reference_payment_entity_id=worksheet.reference_payment_entity_id, abacus_event_id=worksheet.abacus_event_id, statement_period_id=worksheet.statement_period_id, amount=worksheet.amount, currency_code=worksheet.currency_code, revenue_transaction_type=REVENUE_TRANSACTION_TYPES.CLOSING_BALANCE, ) ) return taxable_revenues