|
|||||||
без bill со старыми нормативами
Время создания: 10.09.2020 09:58
Раздел: INFO - JOB - rtneo - Работа над задачами - Создание договоров
Запись: wwwlir/Tetra/master/base/15997030864gbtw1rg2h/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.util.function.*; import com.haulmont.cuba.core.TransactionalDataManager import java.text.DateFormat; import java.text.SimpleDateFormat; //TransactionalDataManager txManager = AppBeans.get(TransactionalDataManager.class) 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') CommitContext ctx = new CommitContext() //Добавляем к уже существующему представлению дополнительное свойство 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"))) def i=5 //Отобрать которые не заходили List<Contragent> contragents = dataManager.load(Contragent.class) .query('select c from rtneo$Contragent c where not c.type = 3 and size(c.contracts) <=2 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 order by c.id') // .query('select c from rtneo$Contragent c where c.personalAccount = \'ААА3812525543\'') .firstResult(i*0) .maxResults(10) .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 }
if(contragent.getRealEstates().stream().anyMatch{e-> e.getOwnType() != null && (e.getOwnType() == 2 || e.getOwnType() == 3)}){ _("${contragent} is rent!") continue; }
HashMap<String, List> mapCreList = new HashMap<>() //Распределяем объекты по группам for(ContragentRealEstate cre : contragent.getRealEstates()){
//Исключаем без категорий if(cre.getCategory() == null || cre.getType() == null)continue
//Исключаем жилые if(cre.getType() != null && 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 // } } _(mapCreList) //Создаем договор и доп
for(String key : mapCreList.keySet()){ Contract contract; Contract suppContract; if(key.equals("cre5")){ contract = createContractForCRE(contragent, year2020, end, mapCreList.get(key)) }else{ contract = createContractForCRE(contragent, start, end, mapCreList.get(key)) suppContract = createSuppContractForCRE(contragent, dataManager.reload(contract, "contract-edit"), start, end, mapCreList.get(key)) } if(contract != null)contragentsLoging.add("${contragent.getInn()} - ${contragent.getName()}") } } //Убираем признак принятия допа //unaccepted(suppContracts) _("*****************************************************************************") //Список обработанных контрагентов contragentsLoging.each({_(it)}) public Contract createContractForCRE(Contragent contragent, Date start, Date end, List<ContragentRealEstate> cre){ ViewRepository vRep = AppBeans.get(ViewRepository.NAME) View viewContract = vRep.getView(Contract.class, "contract-edit") .addProperty("contragent", vRep.getView(Contract.class, "contract-edit").getProperty("contragent").getView().addProperty("notUseReductionFactor"))
ContractService contractService = AppBeans.get(ContractService.class) CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME) SnapshotHistoryService snapshotHistoryService = AppBeans.get(SnapshotHistoryService.NAME); TransactionalDataManager txManager = AppBeans.get(TransactionalDataManager.class)
Contract contract;
//сразу делаем начисление по базовому договору //Нужно определить дату начисления try{ contract = contractService.createNewBaseContractClean(contragent, start, end) // contractService.fillBaseContract(contragent, contract, start, end) processContract(contract, true, false) contract = dataManager.reload(contract, "contract-edit") contractService.fillBaseContractR(contragent, contract, cre); // contract.getPositions().each{_(it.getCategory().getSupportingDocuments())} // contractService.buildContractPositionsForRealEstate(contragent, contract, start, cre);
List<Accrual> accruals = calculationWorker.calculateAccruals(contract.getFrom(), contract.getBefore(), contragent, new Date(), contract); contract.getPositions().each{_(it.getCategory().getNorm())} contract = dataManager.reload(contract, "contract-edit") _("****************") contract.getPositions().each{_(it.getCategory().getNorm())} _(contract) }catch(Exception e){ _(">>>>>>>: ${e.getMessage()}") return contract } // 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); TransactionalDataManager txManager = AppBeans.get(TransactionalDataManager.class)
Contract contract; baseContract = dataManager.reload(baseContract, "contract-view-createSupplementaryAggrements")
//сразу делаем начисление по базовому договору //Нужно определить дату начисления CommitContext ctx = new CommitContext() try{ contract = contractService.createNewSuppContractClean(contragent, baseContract, start, end) contractService.buildContractPositionsForRealEstateSupp(contragent, contract, start, cre); UnaryOperator<Contract> consumer = {e -> e.setTemplate("MSG310820") return e } processContract(consumer.apply(contract), true, false) List<Accrual> accruals = calculationWorker.calculateAccruals(contract.getFrom(), contract.getBefore(), contragent, new Date(), contract); contract = dataManager.reload(contract, "contract-edit") _(contract) }catch(Exception e){ _(">>>>>>>: ${e.getMessage()}") return contract } // calculationWorker.calculateAccruals(contract.getFrom(), contract.getBefore(), contragent, new Date(), contract); // calculationWorker.setupRelevanceOfBills(contract); // snapshotHistoryService.createSnapshotsFromContract(contract);
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 acceptContracts(Contragent contragent){ List<Contract> contracts = dataManager.load(Contract.class) .query('select c from rtneo$Contract c where c.contragent.id = :contragent and c.accepted is null') .parameter("contragent", contragent.getId()) .view("contract-edit") .list() _("${contragent.getId()} = ${contracts.size()}") if(contracts.size() > 0){ _(contragent.getInn()+' - '+contragent.getName()) } contracts.each{ if(it.getMainContract() != null)it.setTemplate("MSG310820") processContract(it, true, false) } } public void processContract(Contract contract, boolean accepted, boolean confirm) { CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME) TransactionalDataManager txManager = AppBeans.get(TransactionalDataManager.class) //получаем предыдущий договор 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) {
//делаем предыдущий неактивным if (lastContract != null) { makeContractObsolete(lastContract, false); } //текущий делаем активным makeContractObsolete(contract, true); //коммит contract.setAccepted(accepted); contract.setAcceptanceDate(new Date()); //Bills // calculationWorker.setupRelevanceOfBills(contract); // snapshotHistoryService.createSnapshotsForContract(contract); dataManager.commit(contract) } else { if(!confirm) dataManager.remove(contract); return } // //Убираем признак принятия допа // 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)} |
|||||||
Так же в этом разделе:
|
|||||||
|
|||||||
|