import uuid from app.config import TaskEnv from app.models.financial_adjust import AdjustFinancialModel from core.repositories.base import BaseRepository from core.service.mongo_db import use_collection class FinancialAdjustRepository(BaseRepository): def __init__(self): super().__init__(collection=TaskEnv.CLN_FINANCIAL_ADJUST, model=AdjustFinancialModel) async def create(self, coding: AdjustFinancialModel): result = await super().create(coding) price = await use_collection(TaskEnv.CLN_PROJECT_PRICE_REPORT).find_one({'project_id': coding.project_id}) if price and coding.amount: await use_collection(TaskEnv.CLN_PROJECT_PRICE_REPORT).update_one( {'project_id': coding.project_id}, {"$inc": {'amount_adjust': coding.amount}} ) return result async def update(self, _id: uuid.UUID, _update: AdjustFinancialModel): _old_dic = await use_collection(TaskEnv.CLN_FINANCIAL_ADJUST).find_one({'_id':_id}) change = 0 result = await super().update(_id, _update) price = await use_collection(TaskEnv.CLN_PROJECT_PRICE_REPORT).find_one({'project_id': _update.project_id}) if price: _old = AdjustFinancialModel(**_old_dic) if 'amount' not in _old_dic and _update.amount: change = _update.amount if _old.amount != _update.amount: change = _update.amount - _old.amount if change != 0 : await use_collection(TaskEnv.CLN_PROJECT_PRICE_REPORT).update_one( {'project_id': _update.project_id}, {"$inc": {'amount_adjust': change}} ) return result async def delete(self, _id: uuid.UUID): _old_dic = await use_collection(TaskEnv.CLN_FINANCIAL_ADJUST).find_one({'_id': _id}) await super().delete(_id) price = await use_collection(TaskEnv.CLN_PROJECT_PRICE_REPORT).find_one({'project_id': _old_dic['project_id']}) if price and 'amount_adjust' in price: await use_collection(TaskEnv.CLN_PROJECT_PRICE_REPORT).update_one( {'project_id': _old_dic['project_id']}, {"$inc": {'amount_adjust': -(_old_dic['amount'])}} ) return True