"""Logic for updating accounting_period actions state.""" from owsresponse import response from abacus_state.constants.constants import ( ACCOUNTING_PERIOD_ACTION_NAMES, ACCOUNTING_RUN_STATUSES, ACTION_STATUSES, ) from abacus_state.constants.error import ERROR_PREVIOUS_ACTIONS_STATUS from abacus_state.models.abacus_state import AbacusState from abacus_state.models.accounting_run import AccountingRun from abacus_state.schemas.abacus_state import AbacusStateDetailSchema from abacus_state.utils.format_error import validation_error def update_accounting_period_state(abacus_state, **params): """Update accounting_period_state by action_state_id.""" parent_table_id = abacus_state.parent_table_id actions = AbacusState.get_formatted_action_statuses( 'accounting_period', parent_table_id ) skip_actions = [ACCOUNTING_PERIOD_ACTION_NAMES.APPROVE_SALES_FILES] if ( abacus_state.action_name not in skip_actions and not _validation_accounting_period_actions( actions, abacus_state.action_name, parent_table_id ) ): return validation_error( ERROR_PREVIOUS_ACTIONS_STATUS.format(abacus_state.action_name) ) abacus_state.update_attributes(**params) AbacusState.commit_changes() return response.Response( message=AbacusStateDetailSchema().dump(abacus_state), status=200 ) def _validation_accounting_period_actions(actions, action_name, period_id): """Validate accounting period's earlier actions are completed or not.""" action_keys = list(actions.keys()) current_action_index = action_keys.index(action_name) validation_status = all( [value == ACTION_STATUSES.COMPLETE for value in actions.values()][ 0:current_action_index ] ) close_period_action = ACCOUNTING_PERIOD_ACTION_NAMES.CLOSE_PERIOD if action_name == close_period_action and validation_status: runs_data = AccountingRun.get_accounting_runs_by_accounting_period_id(period_id) valid_run_statuses = [ ACCOUNTING_RUN_STATUSES.COMMITTED, ACCOUNTING_RUN_STATUSES.SKIPPED, ACCOUNTING_RUN_STATUSES.INVALID, ] if not runs_data: return False return all( run['accounting_run_status'] in valid_run_statuses for run in runs_data ) return validation_status