"""Account search logic.""" from __future__ import annotations from abacus_common_logic.utils.request import BooleanFilter from owsresponse import response from royalties import models from royalties.constants.constants import DEFAULT_PAGE_LIMIT, DEFAULT_PAGE_OFFSET from royalties.schemas.accounting_period import AccountingPeriodDetailSchema accounting_period_detail_schema = AccountingPeriodDetailSchema() accounting_period_model = models.AccountingPeriod() def get_accounting_periods(params): """Search accounts by params.""" accounts_by_params, total_count = _execute_accounting_period_query(params) account_list = accounting_period_detail_schema.dump(accounts_by_params, many=True) return response.Response({'items': account_list, 'total_count': total_count}) def _execute_accounting_period_query(params): """Search for account.""" # Get query config from params query_config = {'is_visible': _get_is_visible_from_params(params)} query_config = {k: v for k, v in query_config.items() if v not in [None, '']} query = models.AccountingPeriod.get_filtered_query(**query_config) # Execute paged query limit = max(int(params.get('limit', DEFAULT_PAGE_LIMIT)), 1) offset = max(int(params.get('offset', DEFAULT_PAGE_OFFSET)), 0) result = _execute_paged_query(query, limit, offset) # Return results and total count return result, query.count() def _execute_paged_query(query, limit: int, offset: int): """Get the offset and limit from the params and execute the paged query.""" return ( query.order_by(accounting_period_model.default_order()) .offset(offset) .limit(limit) .all() ) def _get_is_visible_from_params(params) -> bool | None: return BooleanFilter.parse( params.get('is_visible', None), BooleanFilter.TRUE ).to_bool()