"""Sales File logic.""" from owsresponse import response from royalties import models from royalties.constants import error from royalties.logic import accounting_period as period_logic from royalties.schemas.sales_file import SalesFileDetailSchema, SalesFileUpdateSchema from royalties.utils.format_error import validation_error def create_sales_file(accounting_period_id: int, file_name: str) -> response.Response: """Create a sales file. Args: accounting_period_id (int): ID of the sales_file's parent accounting_period file_name (str): name of the sales_file Returns: an ows response """ error_msg = period_logic.validate_accounting_period_state(accounting_period_id) if error_msg: return validation_error(error_msg) existing = models.SalesFile.find_by_name(file_name) if existing: return validation_error( error.ERROR_ALREADY_EXISTS.format(object_type='Sales File') ) period = models.AccountingPeriod.get_by_id(accounting_period_id) new_sales_file = models.SalesFile.create( accounting_period=period, file_name=file_name ) return response.Response( message=SalesFileDetailSchema().dump(new_sales_file), status=201 ) def update_sales_file(sales_file: models.SalesFile, **params): """Update sales file. Args: sales_file (SalesFile): instance of a SalesFile params (dict): sales_file fields to be updated; can include: amount_usd (decimal): same as amount, but preferred name main_url (str): S3 path of sales_file; optional row_count (int): total rows in sales file; required when amount is present Returns: an ows response """ amount_usd = params.get('amount_usd', sales_file.amount_usd) main_url = params.get('main_url', sales_file.main_url) row_count = params.get('row_count', sales_file.row_count) if (amount_usd and not row_count) or (row_count and not amount_usd): return validation_error(error.ERROR_INVALID_METADATA) errors = SalesFileUpdateSchema( only=( 'amount_usd', 'row_count', 'main_url', ) ).validate(params) if errors: return validation_error(**errors) sales_file.update_attributes( amount_usd=amount_usd, main_url=main_url, row_count=row_count ) models.SalesFile.commit_changes() return response.Response( message=SalesFileDetailSchema().dump(sales_file), status=200 )