"""Accounting run blueprint.""" from abacus_common_logic.views.item_view import ItemView from flask import Blueprint, request from owsrequest import flask_request from owsresponse import response from owsresponse.adaptors.flask import flaskify from royalties.constants.error import ERROR_CODE_AUTHORIZATION from royalties.logic import accounting_run as logic from royalties.models import AccountingRun from royalties.schemas import AccountingRunSchema accounting_run_api = Blueprint( 'accounting_run_api', __name__, url_prefix='/accounting-run' ) class AccountingRunItemView(ItemView): """Operates on an existing accounting run.""" model_class = AccountingRun object_detail_schema = AccountingRunSchema() put_schema = AccountingRunSchema( only=('accounting_run_status', 'summary_export_url') ) def get(self, object_id, **kwargs): """Find an accounting run by its id.""" access_rule_decision = flask_request.verify_rules_access_standalone(request) if not access_rule_decision: return flaskify( response.create_error_response( code=ERROR_CODE_AUTHORIZATION, message='Unauthorized', status=401, ) ) return super().get(object_id, **kwargs) def put(self, object_id, **kwargs): """Update an accounting run by id.""" access_rule_decision = flask_request.verify_rules_access_standalone(request) if not access_rule_decision: return flaskify( response.create_error_response( code=ERROR_CODE_AUTHORIZATION, message='Unauthorized', status=401, ) ) return super().put(object_id, **kwargs) def update_handler(self, obj, **params): """Handle accounting run updates.""" return logic.update_accounting_run(obj, **params) @accounting_run_api.route('//summary/download', methods=['GET']) def download_summary(object_id): """Endpoint to get tsv of accounting run's summary items. Used by frontend-royalties to download a run summary. """ access_rule_decision = flask_request.verify_rules_access_standalone(request) if not access_rule_decision: return flaskify( response.create_error_response( code=ERROR_CODE_AUTHORIZATION, message='Unauthorized', status=401, ) ) summary_url = logic.get_run_summary_items_csv(object_id) return flaskify(response.Response({'summary_url': summary_url})) accounting_run_api.add_url_rule( '/', methods=['GET', 'PUT'], view_func=AccountingRunItemView.as_view('accounting_run'), ) @accounting_run_api.route( '//run-controller/contracts', methods=['GET'] ) def get_contracts_by_accounting_run(accounting_run_id): """Accept an accounting run ID and get a list of contracts.""" access_rule_decision = flask_request.verify_rules_access_standalone(request) if not access_rule_decision: return flaskify( response.create_error_response( code=ERROR_CODE_AUTHORIZATION, message='Unauthorized', status=401, ) ) contract_ids = logic.get_contract_ids_by_accounting_run_id(accounting_run_id) return flaskify(response.Response(contract_ids))