MyTetra Share
Делитесь знаниями!
Start
Время создания: 09.11.2020 17:04
Раздел: INFO - JOB - rtneo - Работа над задачами - Удаление дублей
Запись: wwwlir/Tetra/master/base/1604912656gpp1n9tzny/text.html на raw.githubusercontent.com

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

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

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

import com.groupstp.rtneo.entity.*

import java.util.stream.Collectors

import java.text.SimpleDateFormat;

import com.groupstp.rtneo.service.*;

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


DatePeriodTools periodTools = AppBeans.get(DatePeriodTools.class)

ViewRepository vRep = AppBeans.get(ViewRepository.NAME)

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


View creView = vRep.getView(ContragentRealEstate.class, "_minimal")

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

.addProperty("cadastralNumber")

)

.addProperty("ownType")

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

.addProperty("name")

.addProperty("inn")

.addProperty("personalAccount")

)

.addProperty("introducedWithTechPassport")

.addProperty("createdBy")

.addProperty("validityFrom")

.addProperty("validityTo")


def creList = dataManager.load(ContragentRealEstate.class)

.query('select cre from rtneo$ContragentRealEstate cre join rtneo$EntityesTemporarySet s on cre.id = s.entityId where s.setName = \'doubleAllCRE-11-11-20\' order by cre.realEstate')

.view(creView)

// .firstResult(0)

// .maxResults(1000)

.list().stream()

.filter{e-> e.getOwnType().getId().equals(2)}

.collect(

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



for(def re : creList){

checkCreContragent(re.getValue())

}

//for(def re : creList){

// boolean isTeh = false

// //Если дубли у одного контрагента

// if(re.getValue().size() == 1){

// for(def contragentSet : re.getValue().entrySet()){

// checkCreContragent(contragentSet.getValue())

// }

//

// }else{

// //Несколько контрагентов

//// def contragents = re.getValue().keySet()

// def prevFrom

// def prevTo

// def prevItem;

//

// _("------------")

// for(def contragentSet : re.getValue().entrySet()){

// //Сначала удаляем дубли в рамках одного контрагента

//

// _("${contragentSet.getKey().getInn()} - ${contragentSet.getKey().getName()}")

// //Если объекты внесены по тех паспорту

// if(isAllTechPasport(contragentSet.getValue())){

// prevItem = null

// continue

// }

// checkCreContragent(contragentSet.getValue())

//

//

//

// def prevCre

// for(ContragentRealEstate cre : contragentSet.getValue()){

// _("${cre.getRealEstate().getCadastralNumber()}>> ${cre.getValidityFrom() != null ? df.format(cre.getValidityFrom()) : null} - ${cre.getValidityTo() != null ? df.format(cre.getValidityTo()) : null}")

// prevCre = cre

//

// if(prevCre != null){

//

// }

// }

// prevItem = contragentSet

// }

// }

//// _(re.getValue().size())

//// _("isTeh - ${isTeh}")

//

//}


void checkCreContragent(List<ContragentRealEstate> tehCre){

DatePeriodTools periodTools = AppBeans.get(DatePeriodTools.class)

//Проверка на тех. паспорт

//Все бъекты внесены по тех паспорту

if(isAllTechPasport(tehCre))return

//Есть объекты внесенные по тех паспорту

boolean thereIsTeh = tehCre.stream().anyMatch{e-> Boolean.TRUE.equals(e.getIntroducedWithTechPassport())}

_("---------")

_(tehCre.stream().map{e -> e.getContragent()}.distinct().collect(Collectors.toList()))

_(tehCre.stream().map{e -> e.getRealEstate().getCadastralNumber()}.distinct().collect(Collectors.toList()))

if(thereIsTeh){

//Если есть объекты по тех паспорту

def reNTeh = tehCre.stream().filter{e -> !Boolean.TRUE.equals(e.getIntroducedWithTechPassport())}.distinct().collect(Collectors.toList())


for(def creNTech : reNTeh){

if(isCreatedByUs(creNTech))deleteCRE(creNTech)

}

}else{

//Если нет объектов по тех паспорту

def isLoadDminer = tehCre.stream().anyMatch{e -> isCreatedByUs(e)}

def isNoLoadDminer = tehCre.stream().anyMatch{e -> !isCreatedByUs(e)}

//Если есть объеты из датамайнера и не из него, можно удалить те, что из датамайнера

if(isLoadDminer && isNoLoadDminer){

for(def creNTech : tehCre){

if(isCreatedByUs(creNTech)){

//Если выгружено из датамайнера и есть пересечение дат

def isInclede = tehCre.stream().anyMatch{e-> periodTools.isPeriodIncluded(creNTech.getValidityFrom(), creNTech.getValidityTo(), e.getValidityFrom(), e.getValidityTo())}

_(isInclede)

if(isInclede)deleteCRE(creNTech)

}

}

}

}

}


void deleteCRE(ContragentRealEstate cre){

//Заполняем список на удаление

_("DELETE - ${cre.getContragent().getPersonalAccount()}: ${cre}")

// dataManager.remove(cre)

// flog("${cre.getContragent().getId()}::${cre.getId()}")

}


//Создано нами

boolean isCreatedByUs(ContragentRealEstate cre){

if(cre.getCreatedBy().contains("dataminer"))return true

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

// if(cre.getCreatedBy().equals("admin"))return true

return false

}

boolean isAllTechPasport(List<ContragentRealEstate> list){

return list.stream().allMatch{e-> Boolean.TRUE.equals(e.getIntroducedWithTechPassport())}

}


import com.haulmont.cuba.core.entity.*

import com.haulmont.cuba.core.app.FileStorageService

void flog(String str){

FileStorageService service = AppBeans.get(FileStorageService.NAME)


str += "\n";

FileDescriptor fileDesc = dataManager.load(FileDescriptor.class)

.id(UUID.fromString('b57d596b-ddac-22a8-018f-624aee8d86a4')).view("_local").optional().orElse(null);

try{

byte[] file = service.loadFile(fileDesc);

ByteArrayOutputStream fileOS = new ByteArrayOutputStream();

fileOS.write(file);

fileOS.write(str.getBytes());

service.removeFile(fileDesc);

service.saveFile(fileDesc, fileOS.toByteArray());

}catch(Exception e){

log.debug(e)

}

}

/**

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

*/

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