|
|||||||
После рефакторинга
Время создания: 29.05.2020 18:02
Раздел: INFO - JOB - rtneo - Работа над задачами - Создание договоров
Запись: wwwlir/Tetra/master/base/1590746546bk3lnjv63j/text.html на raw.githubusercontent.com
|
|||||||
|
|||||||
import com.haulmont.cuba.core.global.* import com.groupstp.rtneo.entity.* import com.groupstp.rtneo.service.* import com.groupstp.rtneo.core.bean.* import com.haulmont.cuba.core.global.ViewRepository; import com.haulmont.cuba.core.global.View; import java.text.DateFormat; import java.text.SimpleDateFormat; ContractService contractService = AppBeans.get(ContractService.class) CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME) ViewRepository vRep = AppBeans.get(ViewRepository.NAME) //Нужно ли делать снапшот? Если да, то нужно раскомментировать создание снапшотов //в методах createContractForCRE и createSuppContractForCRE. А также в расчетах по среднему SnapshotHistoryService snapshotHistoryService = AppBeans.get(SnapshotHistoryService.NAME); DateFormat df = new SimpleDateFormat("dd.MM.yyyy"); //Период договоров Date start = df.parse('01.01.2019') Date end = df.parse('31.12.2020') //Разделение объектов Date dateCre1 = df.parse('01.01.2019') Date date0Cre2 = df.parse('02.01.2019') Date date1Cre2 = df.parse('30.04.2019') Date date1Cre3 = df.parse('01.05.2019') Date date1Cre4 = df.parse('31.12.2019') Date year2020 = df.parse('01.01.2020') Date firstSupp = df.parse('07.06.2020') //Добавляем к уже существующему представлению дополнительное свойство isLiving View viewCre = vRep.getView(Contragent.class, "contragent-create-contract") .addProperty("realEstates", vRep.getView(Contragent.class, "contragent-create-contract") .getProperty("realEstates").getView() .addProperty("type", vRep.getView(RealEstateType.class, "_minimal") .addProperty("isLiving"))) //Отобрать которые не заходили List<Contragent> contragents = dataManager.load(Contragent.class) // .query('select c from rtneo$Contragent c where c.user.login is null or (select count(s) from sec$SessionLogEntry s where s.user.login = c.user.login) = 0') // .query('select c from rtneo$Contragent c where size(c.contracts) <=1 and c.user.login is null or (select count(s) from sec$SessionLogEntry s where s.user.login = c.user.login) = 0') // .query('select c from rtneo$Contragent c where not c.type = 3 and size(c.contracts) <=1 and (c.user.login is null or (select count(s) from sec$SessionLogEntry s where s.user.login = c.user.login) = 0) and size(c.realEstates)>0') .query('select c from rtneo$Contragent c where c.personalAccount = \'ААА3808017280\'') .firstResult(0) .maxResults(1000) .view(viewCre) .list() //Список отработанных контрагентов для вывода в лог, если нужно List<String> contragentsLoging = new ArrayList<>() //Если нужно убрать признак принятия допа List<Contract> suppContracts = new ArrayList<>() for(Contragent contragent : contragents){ _(contragent.getInn()+' - '+contragent.getName())
//Удалять старые договора!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! cleanContracts(contragent) //Рачсчеты по среднему для контрагентов у которых нет объектов if(contragent.getRealEstates().size() == 0){ _('Not object') //Создать контракт по среднему т.к. нету объектов // Contract contract = contractService.createNewBaseContractClean(contragent, start, end) // contractService.fillBaseContract(contragent, contract, start, end) // contractService.buildContractPositionsForAWG(contragent, contract, start); // // //сразу делаем начисление по базовому договору // calculationWorker.calculateAccruals(contract.getFrom(), contract.getBefore(), contragent, new Date(), contract); // calculationWorker.setupRelevanceOfBills(contract); // snapshotHistoryService.createSnapshotsFromContract(contract); continue }
HashMap<String, List> mapCreList = new HashMap<>()
//Распределяем объекты по группам for(ContragentRealEstate cre : contragent.getRealEstates()){ //Исключаем жилые if(cre.getType().getIsLiving() != null && cre.getType().getIsLiving() == true)continue
// if(cre.getValidityFrom() == null){ // mapCreList.putIfAbsent("cre4", new ArrayList<ContragentRealEstate>()) // mapCreList.get("cre4").add(cre) // continue // }
if(cre.getValidityFrom() == null || cre.getValidityFrom().compareTo(dateCre1)<=0){ mapCreList.putIfAbsent("cre1", new ArrayList<ContragentRealEstate>()) mapCreList.get("cre1").add(cre) continue }
if(cre.getValidityFrom().compareTo(date0Cre2)>=0 && cre.getValidityFrom().compareTo(date1Cre2)<=0){ mapCreList.putIfAbsent("cre2", new ArrayList<ContragentRealEstate>()) mapCreList.get("cre2").add(cre) continue }
if(cre.getValidityFrom().compareTo(date1Cre3)>=0 && cre.getValidityFrom().compareTo(date1Cre4)<=0){ mapCreList.putIfAbsent("cre3", new ArrayList<ContragentRealEstate>()) mapCreList.get("cre3").add(cre) continue }
if(cre.getValidityFrom().compareTo(date1Cre4)>=0 && cre.getValidityFrom().compareTo(end)<=0){ mapCreList.putIfAbsent("cre5", new ArrayList<ContragentRealEstate>()) mapCreList.get("cre5").add(cre) continue } }
//Создаем договор и доп Contract contract; Contract suppContract; for(String key : mapCreList.keySet()){ if(key.equals("cre5")){ contract = createContractForCRE(contragent, year2020, end, mapCreList.get(key)) }else{ contract = createContractForCRE(contragent, start, end, mapCreList.get(key)) suppContract = createSuppContractForCRE(contragent, contract, start, end, mapCreList.get(key)) } }
suppContracts.add(suppContract) contragentsLoging.add(contragent.getName()) } //Убираем признак принятия допа //unaccepted(suppContracts) _("*****************************************************************************") //Список обработанных контрагентов contragentsLoging.each({_(it)}) public Contract createContractForCRE(Contragent contragent, Date start, Date end, List<ContragentRealEstate> cre){
ContractService contractService = AppBeans.get(ContractService.class) CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME) SnapshotHistoryService snapshotHistoryService = AppBeans.get(SnapshotHistoryService.NAME);
Contract contract; contract = contractService.createNewBaseContractClean(contragent, start, end) contractService.fillBaseContract(contragent, contract, start, end) contractService.buildContractPositionsForRealEstate(contragent, contract, start, cre);
//сразу делаем начисление по базовому договору //Нужно определить дату начисления calculationWorker.calculateAccruals(contract.getFrom(), contract.getBefore(), contragent, new Date(), contract); calculationWorker.setupRelevanceOfBills(contract); // snapshotHistoryService.createSnapshotsFromContract(contract); return contract } public Contract createSuppContractForCRE(Contragent contragent, Contract baseContract, Date start, Date end, List<ContragentRealEstate> cre){ ContractService contractService = AppBeans.get(ContractService.class) CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME) SnapshotHistoryService snapshotHistoryService = AppBeans.get(SnapshotHistoryService.NAME);
Contract contract; baseContract = dataManager.reload(baseContract, "contract-view-createSupplementaryAggrements") contract = contractService.createNewSuppContractClean(contragent, baseContract, start, end) contractService.buildContractPositionsForRealEstateSupp(contragent, contract, start, cre);
//сразу делаем начисление по базовому договору //Нужно определить дату начисления calculationWorker.calculateAccruals(contract.getFrom(), contract.getBefore(), contragent, new Date(), contract); calculationWorker.setupRelevanceOfBills(contract); // snapshotHistoryService.createSnapshotsFromContract(contract);
processContract(contract, true, false)
return contract } public void cleanContracts(Contragent contragent){ List<Contract> contracts = dataManager.load(Contract.class) .query('select c from rtneo$Contract c where c.contragent.id = :contragent') .parameter("contragent", contragent.getId()) .view("_minimal") .list() contracts.each({dataManager.remove(it)}) } public void processContract(Contract contract, boolean accepted, boolean confirm) { CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME) //получаем предыдущий договор Contract lastContract = null; if (contract.getMainContract() != null) { List<Contract> contracts = dataManager.load(Contract.class) .query('select c from rtneo$Contract c where (c.mainContract.id=:mainContract OR c.id=:mainContract) ' + 'AND NOT c.id=:id ' + 'order by c.createTs DESC') .parameter("mainContract", contract.getMainContract().getId()) .parameter("id", contract.getId()) .view("contract-edit") .maxResults(1) .list(); if (contracts.size() > 0) { lastContract = contracts.get(0); } } if (accepted) { contract.setAccepted(accepted); contract.setAcceptanceDate(new Date()); //делаем предыдущий неактивным if (lastContract != null) { makeContractObsolete(lastContract, false); } //текущий делаем активным makeContractObsolete(contract, true); //коммит dataManager.commit(contract); //Bills calculationWorker.setupRelevanceOfBills(contract); // snapshotHistoryService.createSnapshotsForContract(contract); } else { if(!confirm) dataManager.remove(contract); } // //Убираем признак принятия допа // contract.setAccepted(false); // contract.setAcceptanceDate(null); // dataManager.commit(contract)
} private void makeContractObsolete(Contract contract, Boolean reverse) { contract = dataManager.reload(contract, "contract-edit"); CommitContext commitContext = new CommitContext(); for (ContractPosition position : contract.getPositions()) { position.setRelevance(reverse); commitContext.addInstanceToCommit(position); } dataManager.commit(commitContext); } public void unaccepted(List<Contract> contracts){ CommitContext ctx = new CommitContext() for(Contract contract : contracts){ contract.setAccepted(false); contract.setAcceptanceDate(null); ctx.addInstanceToCommit(contract) }
dataManager.commit(ctx) } /** * Логирование */ import com.haulmont.cuba.core.app.serialization.EntitySerializationAPI; import com.groupstp.rtneo.util.JsonUtil; import java.text.DateFormat; import java.text.SimpleDateFormat; private _(Object obj, String... options){ if(obj == null){log("LOG.ERROR: Object is null!!!");return} if(options.size() == 0){log(obj)} for(def option : options){ if(option.equals("str")){log(obj)} if(option.equals("for")){obj.each({_(it)})} if(option.equals("json")){ EntitySerializationAPI entitySerializationAPI = AppBeans.get(EntitySerializationAPI.NAME) try{log(entitySerializationAPI.toJson(obj))} catch(Exception e){log("LOG.ERROR: JSON entity serialization failed")} } if(option.equals("objJson")){ JsonUtil jsonUtil = AppBeans.get(JsonUtil.NAME) try{log.(jsonUtil.toJson(obj))} catch(Exception e){log("LOG.ERROR: JSON object serialization failed")} } if(option.equals("date")){ DateFormat df = new SimpleDateFormat("dd.MM.yyyy"); try{log(df.format(obj))} catch(Exception e){log("LOG.ERROR: Failed date format")} } } } private log(Object obj){log.debug(obj)} |
|||||||
Так же в этом разделе:
|
|||||||
|
|||||||
|