"""Logic for Ledger Correction.""" from typing import Type from abacus_common_logic.connectors.database import db from owsresponse import response from ledger.constants.error import ERROR_LEDGER_CORRECTION_RECORD_ALREADY_EXISTS from ledger.models.ledger_correction import LedgerCorrection from ledger.schemas.ledger_correction import LedgerCorrectionDetailSchema from ledger.utils.currency import validate_currency from ledger.utils.format_error import validation_error from ledger.utils.request import validate_post_request_contains_unique_data def bulk_create(request_body: list) -> Type[response.Response]: """Bulk create logic. Args: request_body(list): POST request body of type LedgerCorrectionSchema Returns: A List of newly created ledger_correction entries. """ ledger_correction_entries = list() try: validate_post_request_contains_unique_data( LedgerCorrectionDetailSchema( many=True, only=('worksheet_correction_id',) ).dump(request_body) ) _has_existing_ledger_records(request_body) for record in request_body: validate_currency(record.get('currency_code')) new_ledger_correction = LedgerCorrection.build(**record) ledger_correction_entries.append(new_ledger_correction) db.session.commit() except Exception as e: return validation_error(str(e)) return response.Response( message=LedgerCorrectionDetailSchema(many=True).dump(ledger_correction_entries), status=201, ) def _has_existing_ledger_records(records: list) -> bool: """Check if worksheet correction records already exist in the ledger_correction table or not. Args: records (list): a POST request body Returns: returns true if worksheet corrections don't exist in ledger_correction table """ worksheet_correction_ids = list( set([record['worksheet_correction_id'] for record in records]) ) results = LedgerCorrection.get_by_worksheet_correction_ids(worksheet_correction_ids) ids = list(set([res.worksheet_correction_id for res in results])) if ids: raise Exception(ERROR_LEDGER_CORRECTION_RECORD_ALREADY_EXISTS.format(ids)) return True