"""Logic around worksheet corrections.""" from typing import Type from abacus_common_logic.connectors.database import db from marshmallow import ValidationError from owsresponse import response from sqlalchemy.exc import DatabaseError from abacus_worksheet.constants.constants import DEFAULT_PAGE_LIMIT, DEFAULT_PAGE_OFFSET from abacus_worksheet.models.worksheet_correction import WorksheetCorrection from abacus_worksheet.schemas.worksheet_correction import ( WorksheetCorrectionDetailSchema, ) from abacus_worksheet.utils.currency import validate_currency_exists from abacus_worksheet.utils.request import validate_pagination_params def bulk_create(request): """Bulk create logic.""" worksheet_corrections = [] try: for record in request: formatted_record = validate_record(record) new_worksheet_correction = WorksheetCorrection.build(**formatted_record) worksheet_corrections.append(new_worksheet_correction) db.session.commit() except (ValidationError, DatabaseError) as e: return response.create_error_response(code='error', status=400, message=str(e)) return response.Response( message=WorksheetCorrectionDetailSchema(many=True).dump(worksheet_corrections), status=201, ) def validate_record(record): """Validate worksheet correction record.""" formatted_record = WorksheetCorrectionDetailSchema( exclude=('worksheet_correction_id',) ).load(record) validate_currency_exists(formatted_record['currency_code']) return formatted_record def get_unapplied_worksheet_corrections( statement_period_id: int, correction_type: str, request_params: dict ) -> Type[response.Response]: """Get a list of unapplied worksheet_correction's by statement_period_id and correction_type. Args: statement_period_id (int): id of the statement period correction_type (str): either royalty_reversal or royalty_correction request_params (dict)(Optional): dict of query string passed to the url - limit(int): the size of page - offset(int): the page number Returns: A list of unapplied worksheet corrections. """ try: WorksheetCorrectionDetailSchema(only=('correction_type',)).load( {'correction_type': correction_type} ) limit = request_params.get('limit', DEFAULT_PAGE_LIMIT) offset = request_params.get('offset', DEFAULT_PAGE_OFFSET) pagination_params = validate_pagination_params(limit, offset) items, total_count = WorksheetCorrection.get_unapplied_worksheet_corrections( statement_period_id, correction_type, **pagination_params ) message = { 'items': WorksheetCorrectionDetailSchema(many=True).dump(items), 'total_count': total_count, } except ValidationError as e: return response.create_error_response(code='error', status=400, message=str(e)) return response.Response(message=message, status=200)