MyTetra Share
Делитесь знаниями!
new
Время создания: 02.04.2021 14:33
Раздел: INFO - JOB - rtneo - Работа над задачами - Создание договоров
Запись: wwwlir/Tetra/master/base/1617345238y3setpera8/text.html на raw.githubusercontent.com

import com.groupstp.rtneo.data.ContainerYardSearchData

import com.groupstp.rtneo.to.ResultCreateContract

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.sys.AppContext

import org.apache.commons.collections.CollectionUtils


import java.util.*

import java.util.concurrent.Callable

import java.util.concurrent.Executors

import java.util.concurrent.TimeUnit

import java.util.stream.*

import java.util.function.*;

import java.util.function.Predicate

import groovy.transform.InheritConstructors;

import java.text.SimpleDateFormat;

//Для оферты нужно установить ее дату в настройках, учеть запрос для получения основных договоров для оферты

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

vRep = AppBeans.get(ViewRepository.NAME)


Date from = df.parse("01-05-2021")

Date to = df.parse("31-12-2021")

//Date dateContract = df.parse("09-06-2021")


Box.log = log

CreatorContract.mixin Box

SuppContragent.mixin Box

SuppRealEstate.mixin Box


countCrated = 0

SuppContragent contragents = null


contragents = new SuppContragentById()

contragents.setUuid("231edbf9-0684-d7b6-0724-a93773110568")


//contragents = new SuppContragentByTemporary()

_("Totals ${contragents.getContragent().size()}")


def securityContext = AppContext.getSecurityContext()

def pool = Executors.newFixedThreadPool(50)

def futureList = []


contragents.getContragent().each { contragent ->

futureList << pool.submit({

AppContext.setSecurityContext(securityContext);

//Удаляем договора контрагентов

if(!checkContracts(contragent)){

_("Skiped clean ${contragent.getId()}")

}else{

// cleanContracts(contragent)

}


// createContract(contragent)

createOnlyOffers(contragent)


} as Callable)

}

pool.awaitTermination(1, TimeUnit.SECONDS)

log.debug('-------------------Result----------------')

futureList.each {log.debug(it.get())}

log.debug(pool)


_(countCrated)

Boolean checkContracts(Contragent contragent){

View contractView = vRep.getView(Contract.class, "_minimal").addProperty("createdBy")

List<Contract> checkContracts = dataManager.load(Contract)

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

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

.view(contractView)

.list()

checkContracts.stream().allMatch{it.getCreatedBy().equals("a.kotvinskiy@groupstp.ru") || it.getCreatedBy().equals("admin")}

}

void createContract(Contragent contragent){

SuppRealEstate suppCre = new SuppRealEstateAll()

List<ContragentRealEstate> cres = suppCre.getRealEstate(contragent);

HashMap<Date, List<ContragentRealEstate>> groupCre = groupRealEstate(cres)

if(groupCre.size() == 0)_("${contragent}: real estate not found")

for(def cre : groupCre.entrySet()){

//Формируем параметры

def params = new ParamsMainContract(cre.getKey())

//В зависимости от даты объекта. Нужно посмотреть как в старой реализации

if(cre.getKey().compareTo(df.parse("17-01-2019")) < 0){

params.contractAttributes.contractDate = df.parse("17-01-2019")

}else{

params.contractAttributes.contractDate = cre.getKey()

}


//Вынести, повторяется код для разных типов договоров

CreatorMainContract creator = new CreatorMainContract()

creator.contragent = contragent

creator.setParams(params)

creator.cres = cre.getValue()


Contract mainContract = creator.create()


//Если договор создан, создаем оферту

if(mainContract != null){

//Если объекты старше 01-06-2019 оферту не создавать

if(cre.getKey().compareTo(df.parse("01-06-2019")) >= 0)continue

createOffer(contragent, mainContract, cre.getValue())

}else{

//Если проблемы при создании договора, чистим ЛК. Нужно сделать чтобы, удалялись только созданные скриптом. И по ключу

log.debug("clean");

// cleanContracts(contragent)

}

}

}

void createOnlyOffers(Contragent contragent){

//Не берем договора по среднему, дата договора меньше чем дата оферты

List<Contract> mainContracts = dataManager.load(Contract.class).query('select distinct c from rtneo$Contract c join c.positions p where c.contragent.id = :contragent and c.mainContract is null and p.contragentRealEstate is not null and c.date <= \'2021-05-01\'')

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

.view("_minimal")

.list()

log.debug(mainContracts)

for(Contract mainContract : mainContracts){

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

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

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

.view("_local")

.list()

createOffer(contragent, mainContract, cre)

}

}

void createOffer(Contragent contragent, Contract mainContract, def cre){

countCrated++



CreatorOfferContract creatorOffer = new CreatorOfferContract()

def paramsOffer = new ParamsOfferContract()

creatorOffer.contragent = contragent

creatorOffer.setMainContract(mainContract)

creatorOffer.setParams(paramsOffer)

creatorOffer.cres = cre


Contract offer = creatorOffer.create()


if(offer != null){

//Пролонгация последних допов

prolongation(offer)

}else{

//Пролонгация договра

prolongation(mainContract)

}

}

void prolongation(Contract contract){


contract = dataManager.reload(contract, viewProlongation())


CalculationWorker calcWorker = AppBeans.get(CalculationWorker.class)

Calendar cal = new GregorianCalendar();

cal.setTime(contract.getBefore())

cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1);

cal.set(Calendar.DAY_OF_MONTH, 1)

Date from = cal.getTime()

cal.set(2021, 11, 31)

Date to = cal.getTime()

_("${from} - ${to}")

calcWorker.calculateAccruals(from, to, contract.getContragent(), contract.getDate(), contract);

}

View viewProlongation(){

return vRep.getView(Contract.class, "contract-edit")

.addProperty("positions", vRep.getView(ContractPosition.class, "_local")

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

.addProperty("category", vRep.getView(RealEstateCategory.class, "_local")

.addProperty("unit", vRep.getView(Unit.class, "_local"))

)

.addProperty("wasteProject", vRep.getView(WasteGenerationProject.class, "_local"))

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

.addProperty("category", vRep.getView(RealEstateCategory.class, "_local"))

.addProperty("wasteGenerationProjects", vRep.getView(WasteGenerationProject.class, "_local"))

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

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

.addProperty("zone", vRep.getView(Zone.class, "_local"))

)

)

)

}

HashMap<Date, List<ContragentRealEstate>> groupRealEstate(List<ContragentRealEstate> cres){

Function<ContragentRealEstate, Date> fValidityFrom = {

return it.getValidityFrom() == null || it.getValidityFrom().compareTo(df.parse('01-01-2019')) < 0 ? df.parse('01-01-2019') : it.getValidityFrom();

}

Function<ContragentRealEstate, Date> fValidityTo = {

return it.getValidityTo() == null ? it.setValidityTo(df.parse('01-01-2222')) : it.getValidityTo()

}

return cres.stream().collect(Collectors.groupingBy({fValidityFrom.apply(it)}))

}


//Methods

void cleanContracts(Contragent contragent){

dataManager.load(Contract.class)

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

.parameter("contragent", contragent)

.view("_minimal")

.list()

.stream().forEach{dataManager.remove(it)}

}


//Classes

//For mixin

public class Box{

static DataManager dataManager = AppBeans.get(DataManager.class);

static def log;

}

//For mixin end



//ParamsCreateContract

interface ParamsCreateContract{}

abstract class ParamsCreateContractAbstract implements ParamsCreateContract, Serializable{

Date from;

Date to;

Date contractDate;

Map<String, Object> contractAttributes = new HashMap<>();

ContractCreatorService contractCreatorService = AppBeans.get(ContractCreatorService.class)

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


abstract void setDefault();


Map<String, Object> get(){

return contractAttributes;

}

Date getLastDayYear(Date date){

Calendar cal = new GregorianCalendar()

cal.setTime(date)

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

cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH))

return cal.getTime()

}

}

@InheritConstructors

class ParamsMainContract extends ParamsCreateContractAbstract{


ParamsMainContract(){

this.from = df.parse("01-01-2019");

this.to = getLastDayYear(from)

setDefault();

}


ParamsMainContract(Date from){

this.from = from;

this.to = getLastDayYear(from)

setDefault();

}

ParamsMainContract(Date from, Date to){

this.from = from;

this.to = to;

setDefault();

}


void setDefault(){

contractAttributes.put("dateFrom", from);

contractAttributes.put("dateTo", to);

contractAttributes.put("contractDate", df.parse("17-01-2019"));

contractAttributes.put("numberContract", contractCreatorService.createContractNumber());

contractAttributes.put("participatesInOldPayments", true);

contractAttributes.put("contractType", ContractType.BASE_CONTRACT);

}

}

@InheritConstructors

class ParamsOfferContract extends ParamsCreateContractAbstract{

ParamsOfferContract(){

setDefault()

}

void setDefault(){

contractAttributes.put("dateFrom", df.parse("01-05-2021"));

contractAttributes.put("dateTo", df.parse("31-12-2021"));

contractAttributes.put("suppAgreementDate", df.parse("09-06-2021"));

contractAttributes.put("baseContractDate", df.parse("01-06-2021"));

contractAttributes.put("numberContract", "1");

contractAttributes.put("participatesInOldPayments", true);

contractAttributes.put("contractType", ContractType.OFFER);

}


}

//ParamsCreateContract end



//CreatorContract

interface CreatorContract{

Contract create();

}

abstract class CreatorContractAbstract implements CreatorContract{

ContractCreatorService creatorService = AppBeans.get(ContractCreatorService.class);

ParamsCreateContract params;

List<ContragentRealEstate> cres;

Contract mainContract;

Contragent contragent;


void printLog(){

log.debug("Contragent: ${contragent.id}")

log.debug("Params: ${params.contractAttributes}")

log.debug("Cres: ${cres}")

log.debug("=========================")

}

}

@InheritConstructors

class CreatorMainContract extends CreatorContractAbstract{

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


Contract create(){

log.debug("MainContract")

printLog()

ResultCreateContract res = creatorService.createContract(contragent, params.contractAttributes, cres, new ArrayList<>() as Collection, new ArrayList<>() as Collection);

log.debug(res.getMessage())

return res.getContract();

}


}

@InheritConstructors

class CreatorOfferContract extends CreatorContractAbstract{

Contract create(){

log.debug("Offer")

printLog()

try{

ResultCreateContract res = creatorService.createSupplementaryAgreement(ContractType.OFFER, mainContract, params.contractAttributes)

log.debug(res.getMessage())

return res.getContract();

}catch(Exception e){

log.debug(e.getMessage())

return null

}

}

}

//CreatorContract end



//SupplierContragent

interface SuppContragent{

List<Contragent> getContragent();

}

abstract class SuppContragentAbstract implements SuppContragent{


}

@InheritConstructors

class SuppContragentById extends SuppContragentAbstract{

UUID uuid;


@Override

List<Contragent> getContragent() {

return [dataManager.load(Contragent.class).id(uuid).view("_minimal").one()]

}

void setUuid(String id){

this.uuid = UuidProvider.fromString(id)

}

}

@InheritConstructors

class SuppContragentByTemporary extends SuppContragentAbstract{

UUID uuid;


@Override

List<Contragent> getContragent() {

String query = 'select c from rtneo$EntityesTemporarySet t join rtneo$Contragent c on t.entityId = c.id where t.setName = \'ContragentRecalc-6Off-16-04-21\''

// query.concat(' and (select count(s) from sec$SessionLogEntry s where s.user.login = c.user.login) = 0 and (select count(p) from rtneo$Payment p where p.inn = c.inn) = 0\')')

return dataManager.load(Contragent.class)

.query(query)

.view("_minimal")

// .firstResult(0)

// .maxResults(10)

.list()

}

void setUuid(String id){

this.uuid = UuidProvider.fromString(id)

}

}

//SupplierContragent end



///SupplierRealEstate

interface SuppRealEstate{

List<ContragentRealEstate> getRealEstate(Contragent contragent);

}

abstract class SuppRealEstateAbstract implements SuppRealEstate{

ViewRepository vRep = AppBeans.get(ViewRepository.class);


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

)

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

// .addProperty("cadastralNumber")

// )

// )

}

}

@InheritConstructors

class SuppRealEstateAll extends SuppRealEstateAbstract{

List<ContragentRealEstate> getRealEstate(Contragent contragent){


String 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 and coalesce(c.excludeFromAccounting, false) = false';

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

.query(query)

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

.view(getViewCre()).list()


return checkCre(cres);

}


List<ContragentRealEstate> checkCre(List<ContragentRealEstate> cres){

//Загнать все условия в map. Вызывать условие по ключу

LinkedList<String> messages = []

def match = cres.stream()

.filter{PredCre.pred

.entrySet()

.stream()

.allMatch{p->

boolean is = ((Predicate<ContragentRealEstate>)p.getValue()).test(it)

if(is)messages.add("${it.getRealEstate().getCadastralNumber()} - ${p.getKey()} - ${is}")

return !is

}

}

.collect(Collectors.toList())


messages.each{log.debug(it)}

return match;

}


class PredCre{

static LinkedHashMap<String, Predicate<ContragentRealEstate>> pred = [:]

static ContainerYardService containerYardService = AppBeans.get(ContainerYardService.class)

static DataManager dataManager = AppBeans.get(DataManager.class)

static{

loadPred()

}

static void loadPred(){


//Прикрепляем КП

Function<ContragentRealEstate, Boolean> setCY = {

String address = it.getRealEstate().getAddress();

if(address!=null && address!="")

{

ContainerYard yard=containerYardService.getNearContainerYard(new ContainerYardSearchData(address),false);

if(yard!=null){

RealEstateContainerYard recy=dataManager.create(RealEstateContainerYard.class);

recy.setContragentRealEstate(it);

recy.setContainerYard(yard);

dataManager.commit(recy);

}

return yard!=null

}

return false

}


pred.put("not category",{

it.getCategory() == null

})


pred.put("is living",{

it.getType() != null && Boolean.TRUE.equals(it.getType().getIsLiving())

})


pred.put("is exclude",{

Boolean.TRUE.equals(it.getExcludeFromAccounting())

})


pred.put("no containers",{

Boolean is = CollectionUtils.isEmpty(it.getContainerYards())

if(is) is = !setCY.apply(it)

return is

})


pred.put("area is null",{

it.getRealEstate().getArea() == null

})


// pred.put("",{

//

// })

}

}

}

//SupplierRealEstate end












/**

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

*/

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

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

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