MyTetra Share
Делитесь знаниями!
по всем
Время создания: 15.10.2020 15:21
Раздел: INFO - JOB - rtneo - Работа над задачами - Создание договоров
Запись: wwwlir/Tetra/master/base/1602746509mhlkb6auir/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;

import com.haulmont.bali.util.Preconditions;


ContractService contractService = AppBeans.get(ContractService.class)

CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME)


//Нужно ли делать снапшот? Если да, то нужно раскомментировать создание снапшотов

//в методах createContractForCRE и createSuppContractForCRE. А также в расчетах по среднему

//SnapshotHistoryService snapshotHistoryService = AppBeans.get(SnapshotHistoryService.NAME);


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


//Только офферта

def onlyOffer = false

clean = true

cleanOffer = false

//Отрефакторить

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

//Date start = df.parse('01.01.2019')

//Date end = df.parse('31.12.2019')

start = df.parse('01.01.2019')

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

dateCre1 = df.parse('01.01.2019')

date0Cre2 = df.parse('02.01.2019')

date1Cre2 = df.parse('30.04.2019')

date1Cre3 = df.parse('01.05.2019')

date1Cre4 = df.parse('31.12.2019')

dateCreEnd = df.parse('31.12.2020')

//Дата допа

contractDate = df.parse("30.06.2019")


Date year2020 = df.parse('01.01.2020')



//Не заполнена дата или она меньше 01.01.2019

//Дата больше date0Cre2 но меньше date1Cre2

//Дата больше date1Cre3 и меньше date1Cre4

//Дата больше date1Cre4 и меньше dateCreEnd


CommitContext ctx = new CommitContext()


//Добавляем к уже существующему представлению дополнительное свойство isLiving

View viewCre = getViewCre()


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

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

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

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


Contract mainContract;


long stP = System.currentTimeMillis();

//363

for(i=0; i<=0; 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 = \'c1c55328-a275-3387-9c2d-66744f7fdfcd\'')

// .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\')')

// .query('select distinct c from rtneo$Contragent c join rtneo$EntityesTemporarySet t on c.id = t.entityId where t.setName = \'oneIsLogin04-10-20CreatedContract\' order by c.id')

// .query('select distinct c from rtneo$Contragent c join rtneo$EntityesTemporarySet t on c.id = t.entityId where size(c.contracts) = 1 and t.setName = \'oneIsNoLogin04-10-20CreatedContract\' order by c.id')

// .query('select distinct c from rtneo$Contragent c join rtneo$EntityesTemporarySet t on c.id = t.entityId where t.setName = \'AllContragentCreateContract_15-10-20\' order by c.id')

.query('select c from rtneo$Contragent c join rtneo$EntityesTemporarySet t on c.id = t.entityId where t.setName = \'AllContragentCreateContract_15-10-20\' and not c.id in (select t.entityId from rtneo$EntityesTemporarySet t where t.setName = \'AllContragentCreateContract_15-10-20-OK\' or t.setName = \'AllContragentCreateContract_15-10-20-Failed\') order by c.id')

.firstResult(i*100)

.maxResults(100)

.view(viewCre)

.list()

long endQ = System.currentTimeMillis();

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

for(Contragent contragent : contragents){

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

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

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

// }

//Паттерн стратегия

// if(onlyOffer) mainContract = getMainContract(contragent)

//Отрефакторить

// HashMap<String, List> mapCreList = onlyOffer ? ['cre1' : getCREFromMainContract(mainContract, viewCre)] : getCREList(contragent, start, dateCre1)

HashMap<String, List> mapCreList = getCREList(contragent, start, dateCre1)

mapCreList.keySet().each{_(it)}

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

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

boolean isCreated = false

if(mapCreList.isEmpty())continue

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

if(cleanOffer)cleanOfferContracts(contragent)

HashMap<String, Object> paramsContract = new HashMap<>()

paramsContract.put("contragent", contragent)

paramsContract.put("start", start)

paramsContract.put("end", end)

paramsContract.put("onlyOffer", onlyOffer)

paramsContract.put("mainContract", mainContract)

for(String key : mapCreList.keySet()){

if(CollectionUtils.isEmpty(mapCreList.get(key)))continue

isCreated = createContract(mapCreList.get(key), paramsContract, contragentsLoging)

}

if(isCreated){

HashMap<String, String> paramsSet = new HashMap<>()

paramsSet.put("entityName", "Contragent")

paramsSet.put("setName", "AllContragentCreateContract_15-10-20")

paramsSet.put("comment", "Создание договоров всем")

addInTemporarySet(contragent, paramsSet, onlyOffer)

}

}

}//FOR

long endP = System.currentTimeMillis();

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

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

//unaccepted(suppContracts)

_("*****************************************************************************")

//Список обработанных контрагентов

contragentsLoging.each({_(it)})


public Contract getMainContract(Contragent contragent){

def mainContract = dataManager.load(Contract.class)

.query('select c from rtneo$Contract c where c.mainContract is null and c.contragent.id = :contragent')

.parameter("contragent", contragent.getId())

.view("_local")

.firstResult(0)

.maxResults(1)

.optional().orElse(null)

Preconditions.checkNotNullArgument(mainContract)

return mainContract;

}


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 >> ${contract}")

}catch(Exception e){

_("Contract >>: ${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 >> ${contract}")

}catch(Exception e){

_("Contract >> ${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 cleanContract(Contract contract){

dataManager.remove(contract)

}

public void cleanOfferContracts(Contragent contragent){

List<Contract> contracts = dataManager.load(Contract.class)

.query('select c from rtneo$Contract c where c.contragent.id = :contragent and c.template = \'MSG310820\'')

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

}


HashMap<String, List> getCREList(Contragent contragent,Date start, Date dateCre1){

HashMap<String, List> mapCreList = new HashMap<>()

//Берем только не покрытые объекты

List<ContragentRealEstate> cres = dataManager.load(ContragentRealEstate.class)

.query('select c from rtneo$ContragentRealEstate c where (select count(cp) from rtneo$ContractPosition cp where cp.contragentRealEstate.id = c.id) = 0 and c.contragent.id = :contragent_id and not c.realEstate.name = \'Земельный участок\' and not c.excludeFromAccounting = true and (c.category.isLiving is null or c.category.isLiving=false)')

.parameter("contragent_id", contragent.getId())

.view(getViewCre1())

.list()

//Распределяем объекты по группам//contragent.getRealEstates()

for(ContragentRealEstate cre : cres){

//Исключаем без категорий

// if(cre.getCategory() == null || cre.getType() == null){

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

// continue

// }


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

_("CRE ${cre.getId()} not category!")

continue

}

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

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

_("CRE ${cre.getId()} is living!")

continue

}

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

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

_("CRE ${cre.getId()} is exclude!")

continue

}

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

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

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

continue

}

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

_("CRE ${cre.getId()} start export!")

continue

}

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

_("Contragent >> ${contragent.getId()} ContainerYards empty")

continue

}

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

_("CRE ${cre.getId()} 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 ${cre.getId()} no 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

// }

//Не заполнена дата или она меньше 01.01.2019

if(cre.getValidityFrom() == null || cre.getValidityFrom().compareTo(dateCre1)<=0){

mapCreList.putIfAbsent("cre1", new ArrayList<ContragentRealEstate>())

mapCreList.get("cre1").add(cre)

continue

}

//Дата больше date0Cre2 но меньше date1Cre2

if(cre.getValidityFrom().compareTo(date0Cre2)>=0 && cre.getValidityFrom().compareTo(date1Cre2)<=0){

mapCreList.putIfAbsent("cre2", new ArrayList<ContragentRealEstate>())

mapCreList.get("cre2").add(cre)

continue

}

// //Дата больше date1Cre3 и меньше date1Cre4

if(cre.getValidityFrom().compareTo(date1Cre3)>=0 && cre.getValidityFrom().compareTo(date1Cre4)<=0){

mapCreList.putIfAbsent("cre3", new ArrayList<ContragentRealEstate>())

mapCreList.get("cre3").add(cre)

continue

}

// //Дата больше date1Cre4 и меньше dateCreEnd

if(cre.getValidityFrom().compareTo(date1Cre4)>=0 && cre.getValidityFrom().compareTo(dateCreEnd)<=0){

mapCreList.putIfAbsent("cre5", new ArrayList<ContragentRealEstate>())

mapCreList.get("cre5").add(cre)

continue

}

_("No set CRE ${cre}")

}

return mapCreList

}


void addInTemporarySet(Contragent contragent, HashMap<String, String> params, Boolean onlyOffer){

Preconditions.checkNotNullArgument(params.get("entityName"))

Preconditions.checkNotNullArgument(params.get("setName"))

Preconditions.checkNotNullArgument(params.get("comment"))

EntityesTemporarySet tempSet = dataManager.create(EntityesTemporarySet.class)

tempSet.setEntityId(contragent.getId())

tempSet.setEntityName(params.get("entityName"))

tempSet.setSetVersion(1)

if(isCreated){

tempSet.setSetName(params.get("setName").toString()+"-OK")

tempSet.setSetComment(params.get("comment"))

}else{

tempSet.setSetName(params.get("setName").toString()+"-Failed")

tempSet.setSetComment(params.get("comment"))

if(clean)cleanContract(contragent)

_("${contragent} cleans contract")

}

dataManager.commit(tempSet)

}

View getViewCre(){

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)

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

)

)

}

//View getViewCre(){

// ViewRepository vRep = AppBeans.get(ViewRepository.NAME)

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

// )

// )

//}

View getViewCre1(){

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)

// return vRep.getView(Contragent.class, "contragent-create-contract")

// .addProperty("realEstates",

return vRep.getView(Contragent.class, "contragent-create-contract")

.getProperty("realEstates").getView()

.addProperty("exportStartDate")

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

.addProperty("isLiving")

)

// )

}

Boolean createContract(List<ContragentRealEstate> cres, HashMap<String, Object> params, List<String> contragentsLoging){

Preconditions.checkNotNullArgument(params.contragent)

Preconditions.checkNotNullArgument(params.start)

Preconditions.checkNotNullArgument(params.end)

Preconditions.checkNotNullArgument(params.onlyOffer)

if(params.onlyOffer) Preconditions.checkNotNullArgument(params.mainContract)

Boolean onlyOffer = params.onlyOffer

Contract contract;

Contract suppContract;

if(!onlyOffer){

contract = createContractForCRE(params.contragent, params.start, params.end, cres)

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

}

suppContract = createSuppContractForCRE(params.contragent, onlyOffer ? params.mainContract : contract, params.start, params.end, cres)


if(suppContract != null){

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

isCreated = true

}

return isCreated

}

List<ContragentRealEstate> getCREFromMainContract(Contract mainContract, View viewCre){

_(mainContract)

return dataManager.load(ContragentRealEstate.class)

.query('select c.contragentRealEstate from rtneo$ContractPosition c where c.contract.id = :contract and c.contragentRealEstate is not null')

.parameter("contract", mainContract.getId())

.view(viewCre.getProperty("realEstates").getView())

.list()

}

/**

* Логирование

*/

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
Яндекс индекс цитирования