MyTetra Share
Делитесь знаниями!
Анализ арендаторов
Время создания: 18.07.2020 13:06
Раздел: INFO - JOB - rtneo - Работа над задачами - Исправление начислений
Запись: wwwlir/Tetra/master/base/1595048780s4m8suyblv/text.html на raw.githubusercontent.com

import com.haulmont.cuba.core.*

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

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


import com.groupstp.rtneo.entity.*;

import com.groupstp.rtneo.service.*;

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

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


import java.text.SimpleDateFormat;

import com.haulmont.bali.util.ParamsMap;

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


import com.haulmont.cuba.core.entity.FileDescriptor

import com.haulmont.cuba.core.app.FileStorageAPI

import java.io.InputStream

import java.io.InputStreamReader

import java.io.ByteArrayOutputStream

import org.apache.commons.io.IOUtils

import java.nio.charset.StandardCharsets;

import com.opencsv.CSVReader;

import org.apache.commons.collections.CollectionUtils

import java.util.stream.Collectors;

/**

*

*/

DatePeriodTools periodTools = AppBeans.get(DatePeriodTools.class)

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

CommitContext cctx = new CommitContext();




//Контрагенты для исключения из файла

String id='170edacc-3aae-8f8d-9f64-60d15064accc'

List<KeyValueEntity> res = resRenters(inToFile(id))


Map<String, Object> instance = ParamsMap.of('df', df, 'cctx', cctx, 'periodTools', periodTools,

'start', df.parse('01-01-2019'),

'end', df.parse('01-12-2019'))


analizeRentersSum(res, instance)





//Строка лога не корректных тарифов в начислениях

//res.each{_("pa - ${it.getValue('pa')}, ctNumber - ${it.getValue('ctNumber')}, aPeriod - ${it.getValue('aPeriod')}, aPrice - ${it.getValue('aPrice')}, correctPrice - ${it.getValue('correctPrice')}, aTotalSum - ${it.getValue('aTotalSum')}, aUpdate - ${it.getValue('aUpdate')}")}



/**

*Main resource data

*

*/


def resRenters(List<String> listInn){

def i=0

String q = 'select r.contragentRealEstate.id, r.payOwner, r.contragentRealEstate.realEstate.cadastralNumber, r.contragentRealEstate.contragent.id, r.contragentRealEstate.contragent.inn, rr.id, rr.contragent.id, rr.contragent.inn, rr.validityFrom, rr.validityTo, (select max(c.before) from rtneo$Contract c where c.contragent.id = r.contragentRealEstate.contragent.id and c.accepted = true), (select max(c.before) from rtneo$Contract c where c.contragent.id = r.renterRecord.contragent.id and c.accepted = true) from rtneo$RealEstateRenter r left join r.renterRecord rr where rr.contragent.inn in :include order by r.contragentRealEstate.contragent.id'

// String q = 'select r.contragentRealEstate.id, r.contragentRealEstate.realEstate.cadastralNumber, r.contragentRealEstate.contragent.id, r.contragentRealEstate.contragent.personalAccount, rr.id, rr.contragent.id, rr.contragent.personalAccount, rr.validityFrom, rr.validityTo from rtneo$RealEstateRenter r left join r.renterRecord rr where r.contragentRealEstate.contragent.personalAccount = \'ААА3812525543\' and r.payOwner = true order by r.contragentRealEstate.contragent.id'

return dataManager.loadValues(q)

.properties("lCreId", "payOwner", "creCad", "lId", "lPA", "tCreId", "tId", "tPA", "vFrom", "vTo", "lPeriodMax", "tPeriodMax")

.parameter("include", listInn)

// .firstResult(i*100)

// .maxResults(100)

.list()


}


/**

*Analize method

*

*/

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

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

void analizeRentersSum(List<KeyValueEntity> res, Map<String, Object> i){

SimpleDateFormat df = i.df

// ("lCreId", "lId", "tCreId", "tId", "vFrom", "vTo")

BillService billService = AppBeans.get(BillService.NAME)


Date dStart = i.start

Date dStop = i.end


Calendar start = Calendar.getInstance()

Calendar end = Calendar.getInstance()

start.setTime(dStart)

end.setTime(dStop)

ViewRepository viewRepository = AppBeans.get(ViewRepository.NAME)

View rrView = viewRepository.getView(RealEstateRenter.class, "_local");

rrView.addProperty('contragentRealEstate', viewRepository.getView(ContragentRealEstate.class, "_minimal"))

List<Accrual> accruals = new ArrayList<>()

List<Accrual> accrualsRent = new ArrayList<>()


String caption = "|Контрагент|Арендатор|Договоров|Конец действия|Кад. номер"

while(start.getTime().compareTo(end.getTime()) <= 0){

caption += "|${df.format(start.getTime())}"

start.add(Calendar.MONTH, 1)

}

_(caption)

for(KeyValueEntity item : res){

start.setTime(dStart)

end.setTime(dStop)

start.set(Calendar.DAY_OF_MONTH, 1)

end.set(Calendar.DAY_OF_MONTH, 1)



accruals = getContragentBillsCRE(item.getValue('lId'), item.getValue('tCreId'))

accrualsRent = getContragentBillsCRE(item.getValue('tId'), item.getValue('tCreId'))



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


HashMap<Date, Object> payLm = new HashMap<>()

HashMap<Date, Object> payTm = new HashMap<>()

while(start.getTime().compareTo(end.getTime()) <= 0){


def period = start.getTime()

payLm.putIfAbsent(period, null)

payTm.putIfAbsent(period, null)

//Месец нужно прибавить сразу, чтобы не зациклилось

start.add(Calendar.MONTH, 1)


if(!i.periodTools.isPeriodIncluded(period, item.getValue('vFrom'), item.getValue('vTo'))){

payTm[period] = ''

payLm[period] = ''

continue

}


Boolean isFact = dataManager.getCount(LoadContext.create(Contract.class).setQuery(

LoadContext.createQuery('select c from rtneo$ContractPosition c where c.contragent.id = :lId and c.contragentRealEstate.id = :lCreId and (c.isFactCalculation = true or c.isFactRecalculation = true) and c.contract.accepted = true and c.period <= :period')

.setParameter("lCreId", item.getValue('lCreId'))

.setParameter("lId", item.getValue('lId'))

.setParameter("period", period)

)) > 0

//Сумма для арендаторов записывается даже при факте арендодателя

def sumInRent = accrualsRent.stream()

.filter{e -> e.getPeriod().compareTo(period) == 0 && (e.getContractPosition().getContragentRealEstate() != null && e.getContractPosition().getContragentRealEstate().getId() == item.getValue('tCreId'))}

.map{p -> p.getTotalSum()}.reduce{u1, u2 -> u1.add(u2)}.orElse(null)


payTm[period] = sumInRent


if(isFact){

payLm[period] = "fact"

continue

}


def sumAcc = accruals.stream()

.filter{e -> e.getPeriod().compareTo(period) == 0 && (e.getContractPosition().getContragentRealEstate() != null && e.getContractPosition().getContragentRealEstate().getId() == item.getValue('tCreId'))}

.map{p -> p.getTotalSum()}.reduce{u1, u2 -> u1.add(u2)}.orElse(null)

if(sumAcc > 0){

payLm[period] = sumAcc

continue

}

if(sumAcc == 0){

payLm[period] = 0

continue

}

periods.add(period)

}


long countL = dataManager.getCount(LoadContext.create(Contract.class).setQuery(

LoadContext.createQuery('select c from rtneo$Contract c where c.contragent.id = :id and c.accepted = true').setParameter("id", item.getValue('lId'))

))

long countR = dataManager.getCount(LoadContext.create(Contract.class).setQuery(

LoadContext.createQuery('select c from rtneo$Contract c where c.contragent.id = :id and c.accepted = true').setParameter("id", item.getValue('tId'))

))


List<RealEstateRenter> rrList = dataManager.load(RealEstateRenter.class)

.query('select rr from rtneo$RealEstateRenter rr where rr.contragentRealEstate.id = :tId')

.parameter('tId', item.getValue('tCreId'))

.view(rrView)

.list()

def tArea = rrList.stream().map{e -> e.getAreaInRent()}.reduce{a1, a2 -> a1.add(a2)}.orElse(0)

def paytArea = rrList.stream().filter{e -> true.equals(e.getPayOwner())}.map{e -> e.getAreaInRent()}.reduce{a1, a2 -> a1.add(a2)}.orElse(0)

String lStart = "|${item.getValue('lPA')}|-pay-${true.equals(item.getValue('payOwner'))}----|${countL}|${item.getValue('lPeriodMax')}|${item.getValue('creCad')}"

String rStart = "|-rent-${tArea}; pay-${paytArea}|${item.getValue('tPA')}|${countR}|${item.getValue('tPeriodMax')}|----------------"


String l = ''

String r = ''

start.setTime(dStart)

end.setTime(dStop)

Boolean isIncorrect = false

Date twoYear = df.parse('01-01-2020')//???????????????????????????????

while(start.getTime().compareTo(end.getTime()) <= 0){

Boolean inReport = false

Date currPeriod = start.getTime()

start.add(Calendar.MONTH, 1)


// if(payLm[currPeriod] == null && payTm[currPeriod] == null)inReport = true

// if(payLm[currPeriod] == 0 && payTm[currPeriod] == null)inReport = true


// if(payLm[currPeriod].equals('fact') || payTm[currPeriod].equals('fact'))inReport = false

// if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] > 0) || (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] > 0))inReport = false

// if((payLm[currPeriod] instanceof String && payLm[currPeriod].equals('')) && (payTm[currPeriod] instanceof String && payTm[currPeriod].equals('')))inReport = false

//Нет начислений

// if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] == 0) && (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] == 0))inReport = true

// if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] == 0) && (payTm[currPeriod] == null))inReport = true

// if((payLm[currPeriod] == null) && (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] == 0))inReport = true

// if((payLm[currPeriod] == null) && (payTm[currPeriod] == null))inReport = true


//Двойные начисления

// if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] > 0) && (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] > 0))inReport = true

// if(payLm[currPeriod].equals('fact') && (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] > 0))inReport = true

// if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] > 0) && payTm[currPeriod].equals('fact'))inReport = true

if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] > 0) && (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] > 0))inReport = true

if(payLm[currPeriod] == null && (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] == 0))inReport = true

// if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] == 0) && payTm[currPeriod] == null)inReport = true

if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] == 0) && !(payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] > 0))inReport = true

if(payLm[currPeriod].equals('fact') && (payTm[currPeriod] instanceof BigDecimal && payTm[currPeriod] > 0))inReport = true

// if((payLm[currPeriod] instanceof BigDecimal && payLm[currPeriod] > 0) && payTm[currPeriod].equals('fact'))inReport = true

// if((payLm[currPeriod] == null) && (payTm[currPeriod] == null))inReport = true

// if(start.getTime().compareTo(twoYear) >= 0)inReport = false

if(start.getTime().compareTo(end.getTime()) >= 0)inReport = false

if(inReport)isIncorrect = true

l+='|' + payLm[currPeriod]

r+='|' + payTm[currPeriod]


}


if(isIncorrect){

// _(item.getValue('lPA'))

// _(item.getValue('tPA'))

_(lStart+l)

_(rStart+r)

_('*')

}


}

}


List<Accrual> getContragentBillsCRE(UUID contragentID,UUID creId)

{

String sqlQuery = 'select e from rtneo$Accrual e where 1=0';


List<Accrual> accruals = new ArrayList<Accrual>();


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

.query('select e from rtneo$Contract e where e.contragent.id = :contragent and e.accepted = true order by e.createTs desc')

.parameter("contragent", contragentID)

.view("_base")

.list();


if (contracts.size() > 0) {

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

Contract lastContract = null;

for (Contract contract : contracts) {

if (lastContract == null) {

lastContract = contract;

sqlQuery = "cast(a.contractPosition.contract.id text)='" + contract.getId().toString() + "' ";

} else {

if (contract.getFrom().before(lastContract.getFrom())) {

sqlQuery = sqlQuery + " or (cast(a.contractPosition.contract.id text)='" + contract.getId().toString() + "' and a.period < '" + sdf.format(lastContract.getFrom()) + "' )";

lastContract = contract;

}

}

}

sqlQuery = 'select a from rtneo$Accrual a where a.contractPosition.contragentRealEstate.id=:creId and a.contragent.id = :contragentID and (' + sqlQuery + ') order by a.period';

accruals = dataManager.load(Accrual.class)

.query(sqlQuery)

.parameter("contragentID", contragentID)

.parameter("creId", creId)

.view("accrual-full")

.list();

}

return accruals;

}



List<String> inToFile(String id){

FileDescriptor fd = dataManager.load(FileDescriptor.class)

.id(UuidProvider.fromString(id))

.view(View.MINIMAL)

.optional().orElse(null);

if(fd == null){throw new RuntimeException("fileNotFound")}

FileStorageAPI fileStorageAPI=AppBeans.get(FileStorageAPI.NAME);

InputStream inputStream=fileStorageAPI.openStream(fd)

CSVReader reader = new CSVReader(new InputStreamReader(inputStream, "UTF-8"));

return reader.readAll().stream()

.map{e->e[0]}.collect(Collectors.toList())

}


/**

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

*/

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