MyTetra Share
Делитесь знаниями!
Объединение договоров
Время создания: 10.12.2020 00:29
Раздел: INFO - JOB - rtneo - Работа над задачами
Запись: wwwlir/Tetra/master/base/16075313988tmzi295jf/text.html на raw.githubusercontent.com

import com.haulmont.cuba.core.global.*

import com.groupstp.rtneo.entity.*

import com.groupstp.rtneo.service.*

import java.text.SimpleDateFormat

import java.util.*

import com.haulmont.cuba.core.global.ViewRepository;

import java.util.stream.Collectors

import java.util.function.*

import com.groupstp.rtneo.core.bean.calculation.*


helper = AppBeans.get(CalculationWorkerHelper.class)

ViewRepository vRep = AppBeans.get(ViewRepository.class)

df = new SimpleDateFormat("yyy-MM-dd");


View cpView = vRep.getView(ContractPosition.class, "_minimal")

.addProperty("contract", vRep.getView(Contract.class, "_minimal")

.addProperty("mainContract", vRep.getView(Contract.class, "_minimal"))

.addProperty("number")

)

.addProperty("contragent", vRep.getView(Contragent.class, "_minimal")

.addProperty("personalAccount")

)

.addProperty("contragentRealEstate", vRep.getView(ContragentRealEstate.class, "_minimal")

.addProperty("contragent", vRep.getView(Contragent.class, "_minimal"))

.addProperty("realEstate", vRep.getView(RealEstate.class, "_minimal")

.addProperty("cadastralNumber")

)

.addProperty("validityFrom")

.addProperty("validityTo")

)



def i=0

List<ContractPosition> cpList = dataManager.load(ContractPosition.class)

.query('select cp from rtneo$ContractPosition cp join rtneo$EntityesTemporarySet t on cp.contract.id = t.entityId where t.setName = \'ContractForSeparation\' and (select count(rr) from rtneo$RealEstateRenter rr where rr.contragentRealEstate.contragent.id = cp.contragent.id) = 0 order by cp.contragent, cp.contract')

// .query('select cp from rtneo$ContractPosition cp where cp.contract.contragent.id = \'0361f8b0-b3dd-1c6a-5ab7-9f061e240fe6\'')

// .query('select cp from rtneo$ContractPosition cp where cp.contract.createdBy = \'a.kotvinskiy@groupstp.ru\' and cp.contract.createTs > \'2020-10-01\' and (select count(cp1.id) from rtneo$ContractPosition cp1 where cp1.contract.id = cp.contract.id)>1 order by cp.contragent.id')

.view(cpView)

.firstResult(i*1000)

.maxResults(1000)

.list()



//_2(cpList)

def groupCp = cpList.stream().collect(Collectors.groupingBy({p-> p.getContragent()},

Collectors.groupingBy({p-> p.getContragentRealEstate()},

Collectors.groupingBy({p-> getValidityFrom(p)},

Collectors.groupingBy({p-> p.getContract()})

)

)

)

)


//_(groupCp)

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

//groupCp.each{_(it)}


//["contractDate" : contractDate, "contractFrom" : contractFrom, "contractTo" : contractTo]

//["contractFrom" : contractFrom, "contractDate" : contractDate, "positions", positions]

List<ContractPosition> cp = new ArrayList<>()

HashMap<Date, List<ContractPosition>> cpMap = new HashMap<>()


HashMap<Contragent, HashMap<Date, ContractTemp>> contractsTemp = new HashMap<>()


Contragent contragent;

for(def contragentIt : groupCp.entrySet()){

HashMap<Date, ContractTemp> tempMap = new HashMap<>()

_2("----------------------------------")

contragent = contragentIt.getKey()

_2(contragent.getPersonalAccount())

//Количество основных договоров у контрагента

def contractCount = cpList.stream().filter{e -> e.getContragent().getId().equals(contragent.getId())}.map{e -> e.getContract()}.filter{e -> e.getMainContract() == null}.distinct().count()

_2("Contracts count = ${contractCount}\n")

ContragentRealEstate realEstate

for(def realEstateIt : contragentIt.getValue().entrySet()){

realEstate = realEstateIt.getKey()

_2("\t"+realEstate.getRealEstate().getCadastralNumber())

Date validityFrom

for(def validityFromIt : realEstateIt.getValue().entrySet()){

validityFrom = validityFromIt.getKey()

_2("\t"+"\t"+df.format(validityFrom))

// validityFrom - это период, начало месяца

tempMap.putIfAbsent(validityFrom, new ContractTemp())

tempMap.get(validityFrom).contragent = contragent

tempMap.get(validityFrom).validityFrom = validityFrom

Contract contract

for(def contractIt : validityFromIt.getValue().entrySet()){

contract = contractIt.getKey()

_2("\t"+"\t"+"\t"+contract.getNumber())

_2("\t"+"\t"+"\t"+"\t"+contractIt.getValue())

for(def cpIt : contractIt.getValue()){

// Date vFrom = cpIt.getContragentRealEstate().getValidityFrom()

_2("\t"+"\t"+"\t"+"\t"+"\t"+"${cpIt.getContragentRealEstate().getValidityFrom()} - ${cpIt.getContragentRealEstate().getValidityTo()}")

Predicate<ContractPosition> pred = {e ->

e.getContragent().getId().equals(contragent.getId()) && e.getContragentRealEstate().getRealEstate().getId().equals(realEstate.getId())

// && e.getContragentRealEstate().getOwnType().equals(TypeOwnership.RENT)

}

//Убрать контрагентов с оплатами

if(!cpIt.getContragent().getId().equals(cpIt.getContragentRealEstate().getContragent().getId())){

// def fil = cpList.stream()

// .filter{e -> pred.test(e)}

// .map{e -> getValidityFrom(e)}

// .sorted()

// .findFirst().orElse(null)

//// _("Is fil ${fil} ${cpIt.getContragentRealEstate().getValidityFrom()}")

// validityFrom = getValidityFrom(fil)

_("Renter!!!")

}

if(contract.getMainContract() == null){

tempMap.get(validityFrom).cpMainList.add(cpIt)

}else{

tempMap.get(validityFrom).cpSuppList.add(cpIt)

}

}

}

}

}

// tempMap.each{_(it.getValue().show())}

// contractsTemp.putIfAbsent(contragent, new HashMap<Date, ContractTemp>())

//Исключаем контрагента если у него был один договор, и после разбиения у него все равно остается один договор. Значит он был правильный.

if(contractCount == 1 && tempMap.size() == 1)continue

contractsTemp.put(contragent, tempMap)

}

_(contractsTemp.size())

contractsTemp.each{ _("---------------------------------")

it.getValue().each{_(it.getValue().show())}

_("\n")}

def count = 0

//for(def c1 : contractsTemp.entrySet()){

//// log.debug("${c1.getKey()} - ${c1.getValue().size()} : ${c1.getValue().size() > 1 ? 'OK' : 'FAL'}")

// if(c1.getValue().size() > 1){

// count++

// _2("*********${c1.getKey()}***********")

// for(def c2 : c1.getValue().entrySet()){

// _2(c2.getKey())

// _2(c2.getValue().show())

//// createContract(c1.getKey(), c2.getValue())

//

// }

// List<Contract> toRemove = dataManager.load(Contract.class)

// .query('select c from rtneo$Contract c where size(c.positions) = 0 and c.contragent.id = :contragent_id')

// .parameter('contragent_id', c1.getKey().getId())

// .view('_local')

// .list()

//// toRemove.each{dataManager.remove(it)}

// }

//}

log.debug(count)


def createContract(Contragent contragent, ContractTemp temp){

ContractCreatorService creator = AppBeans.get(ContractCreatorService.class)

CommitContext contract_ctx = new CommitContext()

Date from = temp.validityFrom

// Date date = temp.date

Date date = temp.cpMainList.stream().map{e -> e.getContragentRealEstate().getValidityFrom() == null ? df.parse("2019-01-01") : e.getContragentRealEstate().getValidityFrom()}.sorted().findFirst().orElse(null)

date = getContractDate(date)

_2(date)

// if(date == null)date = from

Contract contract = metadata.create(Contract.class)

contract.setContragent(contragent)

contract.setCompany(dataManager.getReference(Company.class, UUID.fromString("59794512-fe76-2699-f41e-a1948a94bbe7")))

contract.setDate(date)

contract.setFrom(from)

contract.setBefore(getEndYear(date))

contract.setNumber(creator.createContractNumber())

contract.setAccepted(true)

contract.setPositions(temp.cpMainList)

contract_ctx.addInstanceToCommit(contract)

temp.cpMainList.stream().peek{e -> e.setContract(contract)}.forEach{e -> contract_ctx.addInstanceToCommit(e)}

dataManager.commit(contract_ctx)

List<Accrual> accruals = dataManager.load(Accrual.class)

.query('select a from rtneo$Accrual a where a.contractPosition.contract.id = :contract_id')

.parameter('contract_id', contract.getId())

.view("_local")

.list()

def groupAccrual = accruals.stream().collect(Collectors.groupingBy({p -> p.getPeriod()}))

CommitContext ctx = new CommitContext()

for(def periodAcc : groupAccrual.entrySet()){

_(periodAcc.getKey())

_(periodAcc.getValue())

int number = helper.getNextAccrualNumber()

for(def accrual : periodAcc.getValue()){

_(accrual.getDocumentNumber())

accrual.setDocumentNumber(number)

ctx.addInstanceToCommit(accrual)

}

}

dataManager.commit(ctx)

CommitContext contract_supp_ctx = new CommitContext()

// Date from = temp.validityFrom

// Date date = temp.date

Date dateSupp = temp.cpSuppList.stream().map{e -> e.getContragentRealEstate().getValidityFrom() == null || e.getContragentRealEstate().getValidityFrom() < df.parse("2019-06-30") ? df.parse("2019-06-30") : e.getContragentRealEstate().getValidityFrom()}.sorted().findFirst().orElse(null)

dateSupp = getContractDate(dateSupp)

_2(dateSupp)

// if(date == null)date = from

Contract contractSupp = metadata.create(Contract.class)

contractSupp.setContragent(contragent)

contractSupp.setMainContract(contract)

contractSupp.setCompany(dataManager.getReference(Company.class, UUID.fromString("59794512-fe76-2699-f41e-a1948a94bbe7")))

contractSupp.setDate(dateSupp)

contractSupp.setFrom(from)

contractSupp.setBefore(getEndYear(dateSupp))

contractSupp.setNumber(creator.createContractNumber())

contractSupp.setAccepted(true)

contractSupp.setPositions(temp.cpSuppList)

contractSupp.setTemplate('MSG310820')

contract_supp_ctx.addInstanceToCommit(contractSupp)

temp.cpSuppList.stream().peek{e -> e.setContract(contractSupp)}.forEach{e -> contract_supp_ctx.addInstanceToCommit(e)}

dataManager.commit(contract_supp_ctx)

List<Accrual> accrualsSupp = dataManager.load(Accrual.class)

.query('select a from rtneo$Accrual a where a.contractPosition.contract.id = :contract_id')

.parameter('contract_id', contractSupp.getId())

.view("_local")

.list()

def groupAccrualSupp = accrualsSupp.stream().collect(Collectors.groupingBy({p -> p.getPeriod()}))

CommitContext ctxSupp = new CommitContext()

for(def periodAcc : groupAccrualSupp.entrySet()){

_(periodAcc.getKey())

_(periodAcc.getValue())

int number = helper.getNextAccrualNumber()

for(def accrual : periodAcc.getValue()){

_(accrual.getDocumentNumber())

accrual.setDocumentNumber(number)

ctxSupp.addInstanceToCommit(accrual)

}

}

dataManager.commit(ctxSupp)

}


class ContractTemp{

Contragent contragent

Contract contract

List<ContractPosition> cpMainList = new ArrayList<>()

List<ContractPosition> cpSuppList = new ArrayList<>()

Date date

Date validityFrom

Date validityTo

String show(){

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

Function<ContractPosition, Object> func = {e ->

return e.getContragentRealEstate().getValidityFrom() == null ? null: df.format(e.getContragentRealEstate().getValidityFrom())

}

StringBuilder str = new StringBuilder()

str.append("\ncontragent - ${contragent}")

str.append("\ndate - ${df.format(validityFrom)}")

str.append("\n\ncpMainList - ${cpMainList}")

cpMainList.each{str.append("\n${func.apply(it)} : ${it.getContragentRealEstate().getRealEstate().getCadastralNumber()}")}

str.append("\n\ncpSuppList - ${cpSuppList}")

cpSuppList.each{str.append("\n${func.apply(it)} : ${it.getContragentRealEstate().getRealEstate().getCadastralNumber()}")}

return str.toString()

}

}




Date getValidityFrom(ContractPosition p){

return getValidityFrom(p.getContragentRealEstate().getValidityFrom())

}

Date getValidityFrom(Date date){

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

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

return getFirstDateDay(validityNN)

}

Date getContractDate(Date date){

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

if(validityNN.compareTo(df.parse('2019-01-01'))<= 0) validityNN = df.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()

}



/**

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

*/

import com.haulmont.cuba.core.app.serialization.EntitySerializationAPI;

import com.groupstp.rtneo.util.JsonUtil;

import java.text.DateFormat;

import java.text.SimpleDateFormat;

private _2(Object obj, String... options){

// _(obj, options)

}

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 log2(Object obj){log.debug(obj)}

private log(Object obj){

log.result.append("${obj}\n")

}

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