"""Logic for updating statement_period actions state.""" from owsresponse import response from abacus_state.constants.constants import ( ACTION_STATUSES, PARENT_TABLE_NAMES, STATEMENT_PERIOD_ACTION_NAMES, STATEMENT_PERIOD_ADJUSTMENT_FILE_ACTION_NAMES, ) from abacus_state.constants.error import ( ERROR_ADJUSTMENTS_NOT_APPLIED, ERROR_PREVIOUS_ACTIONS_STATUS, ) from abacus_state.models.abacus_state import AbacusState from abacus_state.models.statement_period_adjustment_file import ( StatementPeriodAdjustmentFile, ) from abacus_state.schemas.abacus_state import AbacusStateDetailSchema from abacus_state.utils.format_error import validation_error def update_statement_period_state(abacus_state, **params): """Update statement_period_state by action_state_id.""" parent_table_id = abacus_state.parent_table_id actions = AbacusState.get_formatted_action_statuses( 'statement_period', parent_table_id ) if not _validate_statement_period_actions( actions, abacus_state.action_name, parent_table_id ): return validation_error( ERROR_PREVIOUS_ACTIONS_STATUS.format(abacus_state.action_name) + ' OR ' + ERROR_ADJUSTMENTS_NOT_APPLIED ) abacus_state.update_attributes(**params) AbacusState.commit_changes() return response.Response( message=AbacusStateDetailSchema().dump(abacus_state), status=200 ) def _validate_statement_period_actions(actions, action_name, parent_table_id): """Validate statement period's earlier actions are completed.""" action_keys = list(actions.keys()) current_action_index = action_keys.index(action_name) previous_action_statuses = list(actions.values())[0:current_action_index] validation_status = all( [status == ACTION_STATUSES.COMPLETE for status in previous_action_statuses] ) # Ensure that adjustments are imported and applied successfully # before closing the statement period. if action_name == STATEMENT_PERIOD_ACTION_NAMES.STATEMENT_PERIOD_CLOSE: # Get adjustment files for specified statement period adjustment_files = ( StatementPeriodAdjustmentFile.get_adjustment_files_by_statement_period_id( parent_table_id ) ) for adjustment_file in adjustment_files: actions = AbacusState.get_formatted_action_statuses( PARENT_TABLE_NAMES.STATEMENT_PERIOD_ADJUSTMENT_FILE, adjustment_file['statement_period_adjustment_file_id'], ) if actions: # If status of upload_file is not complete, then ignore adjustment file if ( actions[STATEMENT_PERIOD_ADJUSTMENT_FILE_ACTION_NAMES.UPLOAD_FILE] != ACTION_STATUSES.COMPLETE ): continue # If status of upload_file is complete but not imported, # then ignore adjustment file if ( actions[STATEMENT_PERIOD_ADJUSTMENT_FILE_ACTION_NAMES.UPLOAD_FILE] == ACTION_STATUSES.COMPLETE and actions[ STATEMENT_PERIOD_ADJUSTMENT_FILE_ACTION_NAMES.IMPORT_FILE ] != ACTION_STATUSES.COMPLETE ): continue validation_status = all( [ status == ACTION_STATUSES.COMPLETE for status in list(actions.values()) ] ) if not validation_status: return validation_status return validation_status