"""Logic for updating sales_file actions state.""" from owsresponse import response from abacus_state.constants.constants import ( ACCOUNTING_PERIOD_ACTION_NAMES, ACTION_STATUSES, SALES_FILES_ACTION_NAMES, ) from abacus_state.constants.error import ( ERROR_PERIOD_IS_NOT_LOCKED, ERROR_SALES_FILE_GET_ELIGIBLE_SALES_IS_NOT_COMPLETE, ) from abacus_state.models.abacus_state import AbacusState from abacus_state.models.sales_file import SalesFile from abacus_state.schemas.abacus_state import AbacusStateDetailSchema from abacus_state.utils.format_error import validation_error def update_sales_file_state(abacus_state, **params): """Update sales_file_state by action_state_id.""" parent_table_id = abacus_state.parent_table_id sales_file = SalesFile.get_sales_file_by_id(parent_table_id) if not sales_file: return validation_error('No sales file found', 404) accounting_period_actions = AbacusState.get_formatted_action_statuses( 'accounting_period', sales_file['accounting_period_id'] ) is_valid = True if abacus_state.action_name == SALES_FILES_ACTION_NAMES.APPROVE_SALES: sales_file_actions = AbacusState.get_formatted_action_statuses( 'sales_file', parent_table_id ) is_valid = _is_valid_for_approval(accounting_period_actions, sales_file_actions) if not is_valid: return is_valid abacus_state.update_attributes(**params) AbacusState.commit_changes() return response.Response( message=AbacusStateDetailSchema().dump(abacus_state), status=200 ) def _is_valid_for_approval( accounting_period_actions: dict[str, str], sales_file_actions: dict[str, str] ) -> response.Response: """Check if sales file can be approved. Args: accounting_period_actions (dict): accounting period actions and their statuses sales_file_actions (dict): sales file actions and their statuses Returns: an ows error response or True """ if ( accounting_period_actions[ACCOUNTING_PERIOD_ACTION_NAMES.DELIVER_SALES_FILES] != ACTION_STATUSES.COMPLETE ): return validation_error(ERROR_PERIOD_IS_NOT_LOCKED) if ( sales_file_actions[SALES_FILES_ACTION_NAMES.GET_ELIGIBLE_SALES] != ACTION_STATUSES.COMPLETE ): return validation_error(ERROR_SALES_FILE_GET_ELIGIBLE_SALES_IS_NOT_COMPLETE) return True