"""Logic for run controllers.""" from owsresponse import response from owsresponse.adaptors.flask import flaskify from royalties import models from royalties.constants import error from royalties.schemas.run_controller import RunControllerDetailSchema def create_run_controller(run_controller_name, contract_type): """Create a new run controller.""" existing = models.RunController.find_by_name(run_controller_name) if existing: return response.create_error_response( code='Error', message='A run controller with that name already exists.', status=400, ) created = models.RunController.build( run_controller_name=run_controller_name, contract_type=contract_type ) models.RunController.commit_changes() message = RunControllerDetailSchema().dump(created) return response.Response(message=message, status=201) def get_contract_run_controller(contract_id): """Get run_controller associated to given contract.""" record = models.RunControllerContract.get_by_contract_id(contract_id).first() if not record: return flaskify( response.create_not_found_response( message=error.ERROR_RUN_CONTROLLER_NOT_ASSOCIATED ) ) else: message = RunControllerDetailSchema().dump(record.run_controller) return flaskify(response.Response(message=message, status=200)) def add_run_controller_to_acct_period(run_controller): """Associate new contract to an open accounting period if one exists. If the new contract is a run controller's first -- and there is an open accounting period -- the run controller needs to be associated to the period via an accounting run. """ statement_period = models.StatementPeriod.get_current_statement_period() current_open_period = None if statement_period: current_open_period = models.AccountingPeriod.get_current_period( statement_period.statement_period_id, run_controller.contract_type ) if current_open_period: models.AccountingRun.create( run_controller=run_controller, accounting_period=current_open_period )