"""Logic for Payment Allocation.""" from typing import Iterable from abacus_common_logic.connectors.database import db from payment.constants.error import ERROR_ALLOCATION_FLOWTHROUGH_MISSED from payment.logic.exceptions import LogicError from payment.models import Items from payment.models.payment_allocation import PaymentAllocationFlowthrough from payment.utils.decorators import no_autoflush def get_flowthrough_allocations_bulk(**params) -> Items[PaymentAllocationFlowthrough]: """Get flowthrough payment allocations with filters. Args: payment_allocation_ids: List of payment allocation IDs to filter by contract_ids: List of contract IDs to filter by payment_statuses: List of payment statuses to filter by ledger_statuses: List of ledger statuses to filter by limit: Maximum number of records to return offset: Pagination offset Returns: Items containing list of PaymentAllocationFlowthrough and total count """ items, total_count = PaymentAllocationFlowthrough.get_filtered_items( limit=params.get('limit'), offset=params.get('offset'), payment_allocation_ids=params.get('payment_allocation_ids'), contract_ids=params.get('contract_ids'), payment_statuses=params.get('payment_statuses'), ledger_statuses=params.get('ledger_statuses'), ) return Items(items, total_count) @no_autoflush def bulk_update_payment_allocations_flowthrough(params: Iterable[dict]) -> None: """Bulk update payment allocations flowthrough.""" ids_mapping = {param['payment_allocation_id']: param for param in params} allocations = PaymentAllocationFlowthrough.get_active_by_ids(ids_mapping.keys()) if missing_ids := ids_mapping.keys() - { allocation.payment_allocation_id for allocation in allocations }: raise LogicError(ERROR_ALLOCATION_FLOWTHROUGH_MISSED.format(missing_ids)) try: for allocation in allocations: attributes = ids_mapping.get(allocation.payment_allocation_id) allocation.update_attributes(**attributes) if 'payment_status' in attributes: allocation.payment_status_modified = allocation.last_modified if 'ledger_status' in attributes: allocation.ledger_status_modified = allocation.last_modified db.session.commit() except Exception as e: db.session.rollback() raise LogicError(str(e)) def bulk_delete_payment_allocations_flowthrough( payment_allocation_ids: Iterable[int], ) -> None: """Bulk delete payment allocations flowthrough.""" PaymentAllocationFlowthrough.soft_delete_by_ids(payment_allocation_ids)