MyTetra Share
Делитесь знаниями!
Пересчет
Время создания: 23.09.2020 12:03
Раздел: INFO - JOB - rtneo - Работа над задачами - Создание договоров
Запись: wwwlir/Tetra/master/base/1600833788wyp0h9e2ox/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.math.RoundingMode;

import org.apache.commons.collections4.*;

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);


df = new SimpleDateFormat("dd.MM.yyyy");

//Период договоров

Date start = df.parse('01.01.2019')

Date end = df.parse('31.12.2019')

//Разделение объектов

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')

contractDate = df.parse("30.06.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("exportStartDate")

.addProperty("type", vRep.getView(RealEstateType.class, "_minimal")

.addProperty("isLiving")

)

)



//Список отработанных контрагентов для вывода в лог, если нужно

List<String> contragentsLoging = new ArrayList<>()

//Если нужно убрать признак принятия допа

List<Contract> suppContracts = new ArrayList<>()


long stP = System.currentTimeMillis();


//def i=1

//for(i=0; i<=205; i++){

// System.out.println(">>>>>>>>>>>>>>>>>>>Counter script = "+i.toString())

long stQ = System.currentTimeMillis();

//Отобрать которые не заходили

List<Contragent> contragents = dataManager.load(Contragent.class)

// .query('select distinct e from rtneo$ContragentRealEstate r join rtneo$Contragent e where r.contragent = e and (r.category.isLiving is null or r.category.isLiving=false) and not r.realEstate.name = \'Земельный участок\' and size(e.contracts)=0 and not e.id in (select t.entityId from rtneo$EntityesTemporarySet t) order by e.id')

// .query('select distinct e from rtneo$ContragentRealEstate r join rtneo$Contragent e on r.contragent = e where ((r.category.isLiving is null or r.category.isLiving=false) and not r.realEstate.name = \'Земельный участок\' and size(e.contracts)=0 and (r.validityFrom is null or r.validityFrom >= \'2019-01-01\') and not r.excludeFromAccounting = true) or (e.id in (select t.entityId from rtneo$EntityesTemporarySet t where not t.setName = \'CreatedContractAllRecalc30-09\')) order by e.id EXCEPT select distinct e from rtneo$Contragent e join rtneo$EntityesTemporarySet t where e.id = t.entityId and t.setName = \'CreatedContractAllRecalc30-09\'')

.query('select c from rtneo$Contragent c where c.id = \'0033395b-c0da-b70f-8e93-fc437b5bd862\'')

// .query('select distinct e from rtneo$ContragentRealEstate r join rtneo$Contragent e on r.contragent = e where (((r.category.isLiving is null or r.category.isLiving=false) and not r.realEstate.name = \'Земельный участок\' and size(e.contracts)=0 and (r.validityFrom is null or r.validityFrom >= \'2019-01-01\') and not r.excludeFromAccounting = true) or (e.id in (select t.entityId from rtneo$EntityesTemporarySet t where not t.setName = \'CreatedContractAllRecalc30-09\'))) and not e.id in (select t.entityId from rtneo$EntityesTemporarySet t where t.setName = \'CreatedContractAllRecalc30-09\')')

// .firstResult(0)

// .maxResults(100)

.view(viewCre)

.list()

long endQ = System.currentTimeMillis();

_("Perfomance ${endQ-stQ}");

for(Contragent contragent : contragents){

_(contragent.getId().toString()+' - '+contragent.getName())

//Удалять старые договора!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

cleanContracts(contragent)

//Рачсчеты по среднему для контрагентов у которых нет объектов

// if(contragent.getRealEstates().size() == 0){

// _('Not object')

// //Создать контракт по среднему т.к. нету объектов

// 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){

// _("${cre} not category or type!")

// continue

// }


if(cre.getCategory() == null){

_("${cre} not category!")

continue

}

//Исключаем жилые

if(cre.getType() != null && Boolean.TRUE.equals(cre.getType().getIsLiving())){

_("${cre} is living!")

continue

}

//Исключаем исключенные из учета

if(Boolean.TRUE.equals(cre.getExcludeFromAccounting())){

_("${cre} is exclude!")

continue

}

//Исключаем земельные уастки

if(cre.getRealEstate().getName() != null && cre.getRealEstate().getName().equals('Земельный участок')){

_("${cre} is land plot!")

continue

}

if(cre.getExportStartDate() != null && cre.getExportStartDate().compareTo(start) > 1){

_("${cre} start export!")

continue

}

if (CollectionUtils.isEmpty(cre.getContainerYards())) {

_("${contragent} ContainerYards empty")

continue

}

if(cre.getRealEstate().getArea() == null){

_("${contragent} area is null")

continue

}

// if(!Boolean.TRUE.equals(cre.getCategory().getUnit().getIsArea()) && (cre.getCalculationAmount() == null || cre.getCalculationAmount() != (int)cre.getCalculationAmount())){

if(!Boolean.TRUE.equals(cre.getCategory().getUnit().getIsArea())){

_("${cre} set calculationAmount")

// def calculationAmount = new BigDecimal(cre.getRealEstate().getArea()*cre.getCategory().getRatio()).setScale(0, RoundingMode.HALF_UP)

// if (calculationAmount.compareTo(BigDecimal.ZERO) == 0) {

// calculationAmount = BigDecimal.ONE;

// }

// cre.setCalculationAmount(calculationAmount)

// dataManager.commit(cre)

}

// 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

// }

}

_("CreList >> ${mapCreList}")

//Создаем договор и доп

boolean isCreated = false

if(mapCreList.isEmpty())continue

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))

if(PersistenceHelper.isNew(contract))dataManager.commit(contract)

suppContract = createSuppContractForCRE(contragent, contract, start, end, mapCreList.get(key))

}

if(suppContract != null){

contragentsLoging.add("${contragent.getId()}|${contragent.getName()}")

isCreated = true

}

}

EntityesTemporarySet tempSet = dataManager.create(EntityesTemporarySet.class)

tempSet.setEntityId(contragent.getId())

tempSet.setEntityName("Contragent")

tempSet.setSetVersion(1)

if(isCreated){

tempSet.setSetName("CreatedContractAllRecalc30-09")

tempSet.setSetComment("Контрагенты без договоров с нежилой")

}else{

tempSet.setSetName("CreatedContractAllRecalc30-09-Failed")

tempSet.setSetComment("Контрагенты без договоров с нежилой (Не удалось создать)")

cleanContracts(contragent)

_("${contragent} cleans contract")

}

dataManager.commit(tempSet)

}

//}//FOR

long endP = System.currentTimeMillis();

_("Perfomance ${endP-stP}");

//Убираем признак принятия допа

//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)

}catch(Exception e){

_(">>>>>>>: ${e.getMessage()}")

return 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)

// DateFormat df = new SimpleDateFormat("dd.MM.yyyy");

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")

e.setDate(contractDate)

return e

}

processContract(consumer.apply(contract), true, false)

List<Accrual> accruals = calculationWorker.calculateAccruals(contract.getFrom(), df.parse("31.12.2020"), contragent, new Date(), contract);

_(contract)

}catch(Exception e){

_(">>>>>>>: ${e}")

return 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(contractDate);

dataManager.commit(contract)

} else {

if(!confirm)

dataManager.remove(contract);

return

}

}

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)}


Так же в этом разделе:
 
MyTetra Share v.0.65
Яндекс индекс цитирования