MyTetra Share
Делитесь знаниями!
Создание договоров по объектам
Время создания: 11.01.2021 17:46
Раздел: INFO - JOB - rtneo - Работа над задачами - Создание договоров
Запись: wwwlir/Tetra/master/base/1610358417c8o0njccjh/text.html на raw.githubusercontent.com

import com.haulmont.cuba.core.entity.Entity

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;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import de.diedavids.cuba.runtimediagnose.groovy.*

import groovy.transform.InheritConstructors;

import com.groupstp.rtneo.util.*;

import java.util.stream.Collectors

import java.time.*;

import static com.groupstp.rtneo.util.DateTimeUtil.PATTERN.*;


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

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

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


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


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

def onlyOffer = false

cleanFailed = true

cleanOffer = false

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

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

start = df.parse('01.01.2019')

end = df.parse('31.12.2020')

contractDate = df.parse('17.01.2019')

//Дата допа

contractDateSupp = df.parse("30.06.2019")

Date year2020 = df.parse('01.01.2020')


interface MyPredicate <T, U, C>{boolean test(T t, U u, C c);}

MyPredicate<Date, Date, ContragentRealEstate> crePred1 = {from, to, cre ->

cre.getValidityFrom() == null || cre.getValidityFrom().compareTo(to)<=0}

MyPredicate<Date, Date, ContragentRealEstate> crePred2 = {from, to, cre ->

cre.getValidityFrom().compareTo(from)>=0 && cre.getValidityFrom().compareTo(to)<=0}

MyPredicate<Date, Date, ContragentRealEstate> crePred3 = {from, to, cre ->

cre.getValidityFrom().compareTo(from)>0 && (cre.getValidityTo() == null || cre.getValidityTo().compareTo(from)>0)}

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

LinkedHashMap<String, HashMap<String, Object>> includedPeriod = new HashMap<>();

includedPeriod.putIfAbsent("cre1", ["from": null, "to": df.parse('01.01.2019'), "pred" : crePred1])

includedPeriod.putIfAbsent("cre2", ["from": df.parse('02.01.2019'), "to": df.parse('30.04.2019'), "pred" : crePred2])

includedPeriod.putIfAbsent("cre3", ["from": df.parse('01.05.2019'), "to": df.parse('31.12.2019'), "pred" : crePred2])

includedPeriod.putIfAbsent("cre5", ["from": df.parse('31.12.2019'), "to": null, "pred" : crePred3])


//Не заполнена дата или она меньше 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=10; i<=119; i++){

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

long stQ = System.currentTimeMillis();

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

def i = 0

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 = \'f93b7dbc-b653-f1c9-53fa-b2238aec9d8c\'')

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

.query('select c from rtneo$Contragent c join rtneo$EntityesTemporarySet t on c.id = t.entityId where t.setName = \'ContragentForSeparationNew\' order by c.id')

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

// .query('select c from rtneo$Contragent c join rtneo$EntityesTemporarySet t on c.id = t.entityId where t.setName = \'ContragentsAllNeededContract-4-27-11-20\' order by c.id')

// .query('select distinct e from rtneo$ContragentRealEstate r join rtneo$Contragent e on r.contragent.id = e.id where (r.category.isLiving is null or r.category.isLiving=false) and not r.realEstate.name = \'Земельный участок\' and (r.excludeFromAccounting is null or not r.excludeFromAccounting = false) and not r.realEstate.area is null')

.firstResult(i*1)

.maxResults(1)

.view(viewCre)

.list()

long endQ = System.currentTimeMillis();

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



for(Contragent contragent : contragents){

_("${contragent.getId()} - ${contragent.getName()}")

//Получаем список объектов

CreListTemplate creList

if(onlyOffer){

creList = new CreListFromContract(contragent, includedPeriod, log)

creList.setMainContracts(getMainContractsForOffer(contragent))

}else{

creList = new CreListFull(contragent, includedPeriod, log)

}

HashMap<Date, List> mapCreList = creList.getList()

// 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("contractDate", contractDate)

paramsContract.put("contractDateSupp", contractDateSupp)


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

// _(mapCreList)

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

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

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

CreatorContracts created

if(onlyOffer){

created = new CreateOnlyOfferContract(log)

created.setMainContracts(getMainContractsForOffer(contragent))

}else{

created = new CreateContract(log)

}

// if(key.equals("cre5")){

// HashMap<String, Object> param2020 = paramsContract.clone()

// param2020.start = df.parse('01.01.2020')

// param2020.end = df.parse('31.12.2020')

// param2020.contractDate = df.parse('09.01.2020')

// param2020.noSupp = true

// (isCreated, contractsKey) = created.createContract(mapCreList.get(key), param2020, contragentsLoging)

// }else{

paramsContract.start = key

paramsContract.end = getEndYear(key)

paramsContract.contractDate = key

if(key.compareTo(df.parse('30.06.2019')) < 0){

paramsContract.contractDateSupp = df.parse('30.06.2019')

paramsContract.noSupp = false

}else{

paramsContract.contractDateSupp = key

paramsContract.noSupp = true

}

_("key")

_(mapCreList.get(key))

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

// }


if(cleanFailed && !isCreated){

if(contractsKey != null)contractsKey.each{

if(it != null)cleanContract(dataManager.reload(it, "_minimal"))

}

_("Cleans contract ${contragent}")

}else{

contracts.addAll(contractsKey)

}

}

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

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

paramsSet.put("setName", "ContragentForSeparationNew-11-01-21")

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

paramsSet.put("isCreated", isCreated)

paramsSet.put("cleanFailed", cleanFailed)

paramsSet.put("contracts", contracts)

// addInTemporarySet(contragent, paramsSet, onlyOffer)


}

Date getEndYear(Date date){

Calendar cal = Calendar.getInstance()

cal.setTime(date)

cal.set(Calendar.MONTH, 11);

cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

return cal.getTime()

}

//}//FOR

long endP = System.currentTimeMillis();

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

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

//unaccepted(suppContracts)

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

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

contragentsLoging.each({_(it)})

_("OK")


/**

*

*/

interface CreListStrategy {

HashMap<String, List> getList();

}

abstract class CreListTemplate implements CreListStrategy{

LinkedHashMap<String, HashMap<String, Object>> predications;

def dfP = new SimpleDateFormat("yyyy-MM-dd");

Contragent contragent;

GroovyConsoleLogger log;

String query;


DataManager dataManager = AppBeans.get(DataManager.class)

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)


CreListTemplate(){


}

CreListTemplate(Contragent contragent, LinkedHashMap<String, HashMap<String, Object>> predications) {

this.contragent = contragent

this.predications = predications

}


CreListTemplate(Contragent contragent, LinkedHashMap<String, HashMap<String, Object>> predications, GroovyConsoleLogger log) {

this(contragent, predications)

this.log = log

}

public View getViewCre(){

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

.getProperty("realEstates").getView()

.addProperty("exportStartDate")

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

.addProperty("isLiving")

)

// )

}

private boolean checkCRE(ContragentRealEstate cre){

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

def start = df.parse('01.01.2019')

boolean isSkip = false

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

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

isSkip = true

}


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

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

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

isSkip = true

}

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

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

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

isSkip = true

}


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

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

// log.debug("CRE ${cre.getId()} is land plot!")

// isSkip = true

// }

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

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

isSkip = true

}


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

log.debug("Contragent >> ${cre.getContragent().getId()} ContainerYards empty")

// isSkip = true

}

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

log.debug("CRE ${cre.getId()} area is null")

isSkip = true

}

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

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

// log.debug("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)

// }

return isSkip

}

public HashMap<String, List> splitCreByPredication(List<ContragentRealEstate> cres) {

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

for (ContragentRealEstate cre : cres) {

boolean isFind = false

if (checkCRE(cre)) continue


for (def item : predications.entrySet()) {

MyPredicate<Date, Date, ContragentRealEstate> pred = (MyPredicate<Date, Date, ContragentRealEstate>) item.getValue().get("pred")

Date from = (Date) item.getValue().get("from")

Date to = (Date) item.getValue().get("to")

if (pred.test(from, to, cre)) {

mapCreList.putIfAbsent(item.getKey(), new ArrayList<ContragentRealEstate>())

mapCreList.get(item.getKey()).add(cre)

isFind = true

break

}

}


if (!isFind) log.debug("No set CRE ${cre}")

}

return mapCreList

}

public HashMap<Date, List> splitCreByValidity(List<ContragentRealEstate> cres) {

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

def groupCp = cres.stream().collect(Collectors.groupingBy({p-> getValidityFrom(p)}))

return groupCp

}

Date getValidityFrom(ContragentRealEstate p){

return getValidityFrom(p.getValidityFrom())

}

Date getValidityFrom(Date date){

Date validityNN = date == null ? dfP.parse('2019-01-01') : date

if(validityNN.compareTo(dfP.parse('2019-01-01'))<= 0) validityNN = dfP.parse('2019-01-01')

return getFirstDateDay(validityNN)

}

Date getContractDate(Date date){

Date validityNN = date == null ? dfP.parse('2019-01-01') : date

if(validityNN.compareTo(dfP.parse('2019-01-01'))<= 0) validityNN = dfP.parse('2019-01-01')

return validityNN

}

Date getFirstDateDay(Date date){

Calendar cal = Calendar.getInstance()

cal.setTime(date)

cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));

return cal.getTime()

}

Date getEndYear(Date date){

Calendar cal = Calendar.getInstance()

cal.setTime(date)

cal.set(Calendar.MONTH, 11);

cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

return cal.getTime()

}

}


@InheritConstructors

class CreListFull extends CreListTemplate{

@Override

HashMap<String, List> getList() {

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

// and (cp.contract.accepted is not null and cp.contract.accepted = true)

this.query = 'select c from rtneo$ContragentRealEstate c where (select count(cp) from rtneo$ContractPosition cp where cp.contragentRealEstate.id = c.id and cp.contragent.id = c.contragent.id) = 0 and c.contragent.id = :contragent_id';

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

.query(query)

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

.view(getViewCre()).list()

// if(cres.stream().anyMatch{e->e.getCategory() == null}){

// log.debug("${contragent.getId()} - category empty.")

// return [:]

// }

log.debug(cres.size())

//Устанавливаем расчетные единицы если их нет

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

cres.each{setCalculationAmountForCRE(it)}

// cres.each{log.debug(it.getCalculationAmount())}

// cres.each{it.setCalculationAmount(getCalculationAmount(it))}

// return splitCreByPredication(cres)

return splitCreByValidity(cres)

}

void setCalculationAmountForCRE(ContragentRealEstate cre){

if(cre.getShare() == null)cre.setShare(BigDecimal.ONE)

if(cre.getCalculationAmount() == null)cre.setCalculationAmount(getCalculationAmount(cre))

dataManager.commit(cre)

}

private BigDecimal getCalculationAmount(ContragentRealEstate cre) {

BigDecimal ratio = null;

RealEstateCategory category = cre.getCategory();

while (ratio == null && category != null) {

ratio = category.getRatio();

if (ratio == null) {

category = category.getParentCategory();

}

}

ratio = ratio == null ? BigDecimal.ONE : ratio;

BigDecimal area = Boolean.TRUE.equals(cre.getIntroducedWithTechPassport()) ?

cre.getParticularArea() : cre.getRealEstate() == null ? null : cre.getRealEstate().getArea();

area = area == null ? BigDecimal.ZERO : area;

if(cre.getShare() != null){

area = area.multiply(cre.getShare())

}

if(!(cre.getOwnType().equals(TypeOwnership.OWN) || cre.getOwnType().equals(TypeOwnership.OTHER)))area = area.getAreaInRent()

return ratio.multiply(area).setScale(2, BigDecimal.ROUND_UP);

}

}

@InheritConstructors

class CreListFromContract extends CreListTemplate{

List<Contract> mainContracts;

@Override

HashMap<String, List> getList() {

if(mainContracts.size() == 0){

log.debug("${contragent.getId()} - no main contract")

return [:]

}

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

this.query = 'select cre from rtneo$ContragentRealEstate cre join rtneo$ContractPosition cp on cre.id = cp.contragentRealEstate.id where cp.contract.id = :contract_id';

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

.query(query)

.parameter("contract_id", mainContracts.get(0).getId())

.view(getViewCre()).list()


if(cres.stream().anyMatch{e->e.getCategory() == null}){

log.debug("${contragent.getId()} - category empty.")

return [:]

}


log.debug(cres.size())

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

// return splitCreByPredication(cres)

return splitCreByValidity(cres)

}

}




abstract class BuildContractAbstract {

ContractService contractService = AppBeans.get(ContractService.class)

CalculationWorker calculationWorker = AppBeans.get(CalculationWorker.NAME)

DataManager dataManager = AppBeans.get(DataManager.class)

ContractCreatorService creator = AppBeans.get(ContractCreatorService.class)

// DateTimeUtil dateTimeUtil = AppBeans.get(DateTimeUtil.class)

GroovyConsoleLogger log;

Contract contract;

HashMap<String, Object> params;

boolean status = 0


Contract create(){

try{

this.contract = create(params)

log.debug("Contract good >> ${contract}")

}catch(Exception e){

log.debug("Contract fail >>: ${e}")//e.getStackTrace()

status = 1

return contract

}

return contract

}


BuildContractAbstract(){


}


BuildContractAbstract(GroovyConsoleLogger log){

this()

this.log = log

}


abstract Contract create(HashMap<String, Object> params);


void processContract(Contract contract, boolean accepted, boolean confirm, Date acceptanceDate) {

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

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 boolean isPeriodIncluded(LocalDate periodStart, LocalDate periodEnd, Date from, Date to) {

Function<Object, LocalDate> funcGetDate = {date -> date instanceof LocalDate ? (LocalDate) date : DateTimeUtil.convertToLocalDate((Date) date)}

if (Objects.nonNull(from)) {

if (periodEnd != null && periodEnd.compareTo(funcGetDate.apply(from)) < 0) {

return false;

}

}

if (Objects.nonNull(to)) {

if (periodStart != null && periodStart.compareTo(funcGetDate.apply(to)) > 0) {

return false;

}

}

return true;

}

}

@InheritConstructors

class ContractForCRE extends BuildContractAbstract{


Contract create(HashMap<String, Object> params){

Preconditions.checkNotNullArgument(params.cres)

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

// contract = contractService.createNewBaseContractClean(params.contragent as Contragent, params.start as Date, df.parse('31.12.2019') as Date)

// // contractService.fillBaseContract(contragent, contract, start, end)

// contractService.fillBaseContractR(params.contragent as Contragent, contract, params.cres as List<ContragentRealEstate>);

log.debug(params)

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

baseParam.put("dateFrom", params.start as Date)

baseParam.put("dateTo", params.end as Date)

baseParam.put("contractDate", params.contractDate as Date)

List<ContragentRealEstate> cres = params.cres as List<ContragentRealEstate>

Function<Object, LocalDate> funcGetDate = {date -> date instanceof LocalDate ? (LocalDate) date : DateTimeUtil.convertToLocalDate((Date) date)}

LocalDate suppDateFrom = baseParam.containsKey("dateFrom") ? funcGetDate.apply(baseParam.get("dateFrom")) : DateTimeUtil.convertToLocalDate(contract.getFrom());

LocalDate suppDateTo = baseParam.containsKey("dateTo") ? funcGetDate.apply(baseParam.get("dateTo")) : DateTimeUtil.convertToLocalDate(contract.getBefore());


cres = cres.stream().peek{e-> log.debug(isPeriodIncluded(suppDateFrom as LocalDate, suppDateTo as LocalDate, e.getValidityFrom() as Date, e.getValidityTo() as Date))}.filter{e-> isPeriodIncluded(suppDateFrom, suppDateTo, e.getValidityFrom() as Date, e.getValidityTo() as Date)}.collect(Collectors.toList())

if(cres.isEmpty())return null

try{

contract = creator.createContract(params.contragent as Contragent, baseParam,

new ArrayList<>(),

cres as List<ContragentRealEstate>,

new ArrayList<>())

}catch(Exception e){

log.debug(e.getStackTrace())

}

return contract

}

}

@InheritConstructors

class SuppContractForCRE extends BuildContractAbstract{

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

Contract create(HashMap<String, Object> params){

Preconditions.checkNotNullArgument(params.cres)

Preconditions.checkNotNullArgument(params.baseContract)

// params.baseContract = dataManager.reload(params.baseContract as Entity, "contract-view-createSupplementaryAggrements")

//

//

//

// contract = contractService.createNewSuppContractClean(params.contragent as Contragent, params.baseContract as Contract, params.start as Date, params.end as Date)

// contractService.buildContractPositionsForRealEstateSupp(params.contragent as Contragent, contract, params.start as Date, params.cres as List<ContragentRealEstate>);

//

// UnaryOperator<Contract> consumer = {e ->

// e.setTemplate("MSG310820")

// e.setDate(df.parse("30.06.2019"))

// return e

// }

//

// processContract(consumer.apply(contract), true, false, params.acceptanceDate as Date)

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

//

// createSupplementaryAgreement(ContractType contractType, Contract contract, Map<String, Object> contractAttributes)

// LocalDate suppDateFrom = contractAttributes.containsKey("dateFrom") ? funcGetDate.apply(contractAttributes.get("dateFrom")) : convertToLocalDate(contract.getFrom());

// LocalDate suppDateTo = contractAttributes.containsKey("dateTo") ? funcGetDate.apply(contractAttributes.get("dateTo")) : convertToLocalDate(contract.getBefore());

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

offerParam.put("dateFrom", params.start as Date)

offerParam.put("dateTo", df.parse("31.12.2020"))

contract = creator.createSupplementaryAgreement(ContractType.OFFER, params.baseContract, offerParam)

processContract(contract, true, false, params.acceptanceDate as Date)

return contract

}

}


interface CreateContractStrategy{

Contract getContract();

}

abstract class CreatorContracts implements CreateContractStrategy{

DataManager dataManager = AppBeans.get(DataManager.class)

GroovyConsoleLogger log;

CreatorContracts(){

}

public CreatorContracts(GroovyConsoleLogger log){

this.log = log

}

}

@InheritConstructors

class CreateContract extends CreatorContracts{

@Override

Contract getContract() {

return null

}

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

log.debug("cres")

log.debug(cres)

Preconditions.checkNotNullArgument(params.contragent)

Preconditions.checkNotNullArgument(params.start)

Preconditions.checkNotNullArgument(params.end)

// params.putIfAbsent("cres", cres)

params.cres = cres

// log.debug(params)

Contract contract = null;

Contract suppContract = null;

def isCreated = false


ContractForCRE contractForCRE = new ContractForCRE(log);

contractForCRE.setParams(params)

try{

contract = contractForCRE.create()

}catch(Exception e){

log.debug(e)

}


//Не создан договор

if(contract == null){

return [isCreated, [contract,suppContract]]

}

//Если не нужен доп

if(Boolean.TRUE.equals(params.noSupp)){

if(contract != null)isCreated = true

return [isCreated, [contract,null]]

}

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

params.put("baseContract", contract)

params.start = DateTimeUtil.parseDate("2019-06-01", DateTimeUtil.PATTERN.yyyy_h_MM_h_dd)

SuppContractForCRE suppContractForCRE = new SuppContractForCRE(log);

suppContractForCRE.setParams(params)

suppContract = suppContractForCRE.create()


if(suppContract != null){

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

isCreated = true

}

log.debug("status ${contractForCRE.status}, ${suppContractForCRE.status}")

if(contractForCRE.status.equals(1) || suppContractForCRE.status.equals(1))isCreated = false

return [isCreated, [contract,suppContract]]

}

}

@InheritConstructors

class CreateOnlyOfferContract extends CreatorContracts{

List<Contract> mainContracts;

@Override

Contract getContract() {

return null

}

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

Preconditions.checkNotNullArgument(params.contragent)

Preconditions.checkNotNullArgument(params.start)

Preconditions.checkNotNullArgument(params.end)

params.putIfAbsent("cres", cres)

def isCreated = false

log.debug(params)

if(mainContracts.size() == 0)return [isCreated, []]

params.put("baseContract", mainContracts.get(0))


SuppContractForCRE suppContractForCRE = new SuppContractForCRE(log);

suppContractForCRE.setParams(params)

Contract suppContract = suppContractForCRE.create()

if(suppContract != null){

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

isCreated = true

}

log.debug("status ${suppContractForCRE.status}")

if(suppContractForCRE.status.equals(1))isCreated = false

return [isCreated, [suppContract]]

}

}

/**

*

*

*/


public List<Contract> getMainContracts(Contragent contragent){

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

.list()

}

public List<Contract> getMainContractsForOffer(Contragent contragent){

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

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

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

.view("_local")

.list()

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

.list()

mainContract.removeAll(suppContract)

return mainContract

}

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 unaccepted(List<Contract> contracts){

CommitContext ctx = new CommitContext()

for(Contract contract : contracts){

contract.setAccepted(false);

contract.setAcceptanceDate(null);

ctx.addInstanceToCommit(contract)

}


dataManager.commit(ctx)

}


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

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

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


EntityesTemporarySet tempSet = dataManager.create(EntityesTemporarySet.class)

tempSet.setEntityId(contragent.getId())

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

tempSet.setSetVersion(1)

if(params.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"))

}

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

)

)

}

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

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